有一個問題在這裏,我需要這個循環來打印新的代碼行到一個文件,直到它做什麼是打印1行然後第二次失敗,java while while try catch,can not print to a new line
永遠無法得到它打印到另一條線,下面是代碼
public class study {
public static void main(String[] args) throws IOException{
BufferedWriter post = null;
File file = new File("text.txt");
if(!file.exists()){
file.createNewFile();
}
boolean promptUser = true;
FileWriter fileWriter = new FileWriter(file);
post = new BufferedWriter(fileWriter);
try {
while(promptUser){
System.out.println("enter age "); //get age
Scanner getage = new Scanner(System.in);
int age= getage.nextInt();
if(age <20 || age>50){ //age range
System.out.println("age must be between 20 and 50");
System.exit(0);
}
System.out.println("enter name "); //get name
Scanner getname = new Scanner(System.in);
String name= getname.nextLine();
System.out.println("enter email "); //get email
Scanner getarea = new Scanner(System.in);
String email= getarea.nextLine();
post.write(age + "\t"); <===== fails here on second run
post.write(name + "\t");
post.write(email + "\t");
post.newLine();
post.close();
System.out.println("enter quit to quit or any key to continue");
Scanner options = new Scanner(System.in);
String option = options.nextLine();
if(option.equalsIgnoreCase("quit")){
System.out.println("goodbye!");
System.exit(0);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
爲什麼不使用bufferedWriter.newLine()的;每個條目之後,而在你的情況寫入文件,即post.newLine(); – 2014-10-29 05:12:55
我在關閉之前做了 – user3766275 2014-10-29 05:15:51
爲什麼不在每個post.write()後都在嘗試 – 2014-10-29 05:17:19