【发布时间】:2019-10-17 12:27:10
【问题描述】:
问题发生在我的 while 代码中,它首先获取用户输入并将其放入文本文件并询问是否要再次回答,但每个用户都这样做并结束循环它只接受最新的用户输入并且只是覆盖用户之前输入的内容。但这不是我想从我的代码中做的。相反,新答案应该在文本文件的新行上。
public static void main(String[] args) throws IOException {
// TODO code application logic here
int saldo = 10000;
String anw = "j";
int cost;
try{
File folder = new File("folderName");
folder.mkdir();
File f = new File(folder, "file1.txt"); //file to folder
f.createNewFile(); //skapar fil
//Scanner fileIn = new Scanner(f);
System.out.println("File path" +f.getPath());
//.----------------------------------
while(anw.equals("j")){
Scanner in = new Scanner(System.in);
FileWriter fWriter ;// removed null
BufferedWriter writr;// removed null
System.out.println("Ange utgiftspost:"); //post
String post = in.nextLine();
System.out.println("Ange kostnad:"); //kost
cost=in.nextInt();
in.nextLine();
saldo = +saldo -cost;
System.out.println("saldo:" +saldo);
System.out.println("Vill du mata in fler uppgifter? (j/n) :");
anw = in.nextLine();
String fileContent = "---"+post+"---"+cost+"---"+saldo;
fWriter = new FileWriter(f);
writr = new BufferedWriter(fWriter);
writr.write(fileContent);
writr.newLine();
if (anw.equals("n")) {
writr.close();
//writer.close();
//System.out.println("---"+post+"---"+cost+"---"+saldo);
}
} //frågan slut
}//try
//Scanner fileIn = new Scanner(f);
catch(Exception e){
System.err.println(e.getMessage());
}
}
【问题讨论】:
标签: java string filewriter bufferedwriter