Bonjour,
Il y a un petit décalage que vous remarquerez lorsque vous l'executerez. Vous verrez la petite astuce que je me suis trouvée, mais elle ne fonctionne pas très bien.
package javaapplication5;
/**
* @author sandé
*/
import java.io.*;
import java.util.Scanner;
public class JavaApplication5 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner sc = new Scanner(System.in);
int achat;
int ventes;
int benefice;
int enr;
File f = new File("Bilan.txt");
try{
boolean ajout = true;
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(f, ajout)));
pw.println(" ");
pw.println(" +-----------------------------------------------------------+");
pw.println(" ! ACHAT ! VENTE ! BENEFICE !");
pw.println(" +-----------------------------------------------------------+");
System.out.println("combien d enregistrements ?");
enr = sc.nextInt();
for(int i=1; i<=enr; i++){
System.out.println("achat: ");
achat = sc.nextInt();
System.out.println("vente: ");
ventes = sc.nextInt();
benefice = ventes - achat;
pw.println(" ! "+achat+" ! "+ventes+" ! "+benefice+" !"); // ecriture dans le fichier
System.out.println(" ! "+achat+" ! "+ventes+" ! "+benefice+" !"); // ecriture a l'ecran
// pw.println(" +-----------------+-------------------+---------------------+"); // tracer un trait dans le fichier (ca fonctionne. je lia enleve pour que tu voix le decalage)
}
// REMARQUE : il y a un petit decalage. C'est pour resoudre ce probleme que j'ai decise d'ouvrir 2 fois le me fichier pour ecrire dedans.
pw.close();
}catch(Exception Ex){
System.out.println("Probleme avec le fichier...");
}
}
}
cs_Julien39
Messages postés6414Date d'inscriptionmardi 8 mars 2005StatutModérateurDernière intervention29 juillet 2020371 1 oct. 2012 à 11:09
Salut,
Je n'exécute jamais les codes, mais je crois comprendre ce qui t'arrive, tu voudrais faire un vrai tableau mais étant donné que tu ne maîtrises pas la taille du texte entré, tes colonnes ne sont pas propres.
Je te conseil d'utiliser ces fonctions :
public String espaces(int nombre){
StringBuilder sb = new StringBuilder();
for(int i=0; i<nombre; i++){
sb.append(" ");
}
return sb.toString();
}
public String creerLigne(String achat, String vente, String benefice){
StringBuilder sb = new StringBuilder();
sb.append(" ! ");
sb.append(achat);
sb.append(espaces(16-achat.length));
// idem pour les autres
return sb.toString();
}