我正在尝试编写一个程序,要求用户以他们想保存的打油诗的名字pu,然后创建一个以该打油诗的名字命名的文件,然后要求他们编写打油诗。然后保存到文件。我有这段代码可用于创建文件,但是当我尝试将打油条写入文件时,似乎陷入了循环并不断地等待输入文件的第一行。任何帮助将不胜感激?
public void start () {
System.out.println("<<THIS PROGRAM SAVES A LIMERICK THAT YOU HAVE WROTE>>");
}
public File create () {
System.out.println("<<ENTER THE NAME OF THE LIMERICK>>");
name = scan.nextLine();
nameFile = name + ".txt";
File file = new File(nameFile);
try {
if (file.createNewFile() ) {
System.out.println("<<FILE CREATED>>");
} else {
System.out.println("<<FILE ALREADY EXISTS>>");
}
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
public void write () {
Limerick write = new Limerick();
File file = write.create();
System.out.println("<<ENTER THE LIMIRICK>>");
PrintWriter pw;
try {
pw = new PrintWriter (new BufferedWriter (new FileWriter(file)));
limerick = scan.nextLine();
while (!(limerick.equals("DONE"))) {
pw.println(limerick);
}
pw.close();
System.out.println("<<LIMERICK WRITTEN TO FILE>>");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main (String args[]) {
Limerick method = new Limerick();
method.start();
method.write();
}
答案 0 :(得分:2)
在以下循环中,limerick的值从未更新,因此进入无限循环
while (!(limerick.equals("DONE"))) {
pw.println(limerick);
}
将其更改为以下内容:
while (!(limerick.equals("DONE"))) {
pw.println(limerick);
limerick = scan.nextLine();
}
因此,每次迭代后,limerick
的值都会更新。
答案 1 :(得分:2)
您需要在循环内运行scan.nextLine()
:
while (!((limerick = scan.nextLine()).equals("DONE"))) {
pw.println(limerick);
}