[英]How do I use a string conditional in a while loop, java?
public class Diary {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
PrintWriter output = null;
try {
output = new PrintWriter (new FileOutputStream("diaryLog"));
} catch (FileNotFoundException e) {
System.out.println("File not found");
System.exit(0);
}
//Ok, I will ask the date for you here:
System.out.println("Enter the date as three integers separated by spaces (i.e mm dd yyyy):");
int month = input.nextInt();
int day = input.nextInt();
int year = input.nextInt();
//And print it in the file
output.println("Date: " + month +"/" + day + "/" + year);
System.out.println("Begin your entry:");
String entry= input.next();
while("end".equals(entry))
{
output.print(entry + " ");
}
output.close();
System.out.println("End of program.");
}
}
该程序的目标是输入并创建一个日记条目,并在输入单词end时将输入输出到文件中。 当我编译时,当我输入end并且我的日记条目未保存在输出文件中时,程序不会终止。
在您的代码中,如果entry
值为end
则循环将继续。 但是,您想要反向操作,请使用!
运营商。 同样,您也没有在循环内使用新值重新分配entry
,因此,如果条目的第一个值本身是end
,将导致无限循环。
您需要将值重新分配给entry
:
String entry;
while(!"end".equals(entry = input.next())) {// I had used `!` logical operator
output.print(entry + " ");
}
在循环的每次迭代中,您都希望任务用户更多的输入。 因为您想让用户至少输入一次内容,所以应该使用do-while
循环,例如...
String entry = null;
do {
entry = input.nextLine();
} while (!"end".equals(entry));
有几处更改。 您应该拥有的是:
String entry= input.next();
output.print(entry + " ");
while(! "end".equals(entry))
{
entry= input.next();
}
output.close();
System.out.println("End of program.");
意图是,当用户不输入“ end”时继续阅读。
上面给出的解决方案是正确的,但不要忘记关闭input
否则,在Eclipse中,当您尝试打开文本文件时,将遇到堆大小问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.