由于某种原因,这个程序将不loop正确,它应该等待用户输入,然后决定天气它应该循环.相反,它跳过用户输入部分,直接决定它需要loop,然后允许用户输入到被考虑在内.
例如,它要求一个数字,我输入5,然后它说"你想再去一次吗?" "请使用是或否,区分大小写!" "你想再去一次吗?".在它运行之后它将接受用户输入,我想到使用睡眠(2000),但我不希望它只是跳过并假设用户没有放什么事.我很难过!请记住,这是我第二天使用java.我是一个newbie,这只是我正在进行的第三个项目.我在另一个程序上遇到了这个问题,但我设法解决它很好.但是这个似乎不想以同样的方式工作,尽管我的框架完全相同.
do {
System.out.println("would you like to go again?");
if (input.hasNextLine()){
again = input.nextLine();
if (again.equals("yes")){
yon2 = false;
dateconverter.main(args);
}else if (again.equals("no")){
System.out.println("good bye");
Thread.sleep(4000);
System.exit(0);
}else{
yon2 = true;
System.out.println("Please use either yes or no. caps sensative!");
}
}
} while (!(yon2 = false));
Run Code Online (Sandbox Code Playgroud)
Java循环正确.但是,这yon2 = false是一项任务,而不是一项比较.
因此循环等效于:
do {
// ..
yon2 = false; // assign! :(
} while (!yon2);
Run Code Online (Sandbox Code Playgroud)
所以Java正在按照它所做的去做.
现在,尽管如此,我认为另一个问题是对变量的使用感到困惑.考虑一下:
boolean askAgain = true;
do {
System.out.println("would you like to go again?");
if (input.hasNextLine()){
String again = input.nextLine();
if (again.equals("yes")){
// Finally done asking
askAgain = false;
dateconverter.main(args);
} else if (again.equals("no")){
System.out.println("good bye");
Thread.sleep(4000);
System.exit(0);
} else {
// If we're here, we still need to ask again
System.out.println("Please use either yes or no. caps sensative!");
}
} else {
// no more lines! do something sensible
System.exit(0);
}
// Loop while we need to ask again!
// Note that the negative is removed
} while (askAgain);
Run Code Online (Sandbox Code Playgroud)
但是,花一点时间来重构这个允许以后更容易阅读的内容并避免完全处理标志:
boolean promptKeepPlaying (Scanner input) {
while (input.hasNextLine()){
System.out.println("would you like to go again?");
String again = input.nextLine();
if (again.equalsIgnoreCase("yes")){
return true;
} else if (again.equalsIgnoreCase("no")){
return false;
} else {
System.out.println("Please use either yes or no.");
}
}
// no more lines
return false;
}
// somewhere else
if (promptKeepPlaying(input)) {
// restart game
dateconverter.main(args);
} else {
// exit game
System.out.println("good bye");
Thread.sleep(4000);
System.exit(0);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
130 次 |
| 最近记录: |