Java帮助用户输入中断While循环
我只是做了一个简单的数学辅导游戏,但我似乎不知道如何用用户输入来打破它。这就是我目前得到的任何帮助都是感激的。我现在知道如何使用.equals比较字符串,但我不断地遇到错误 “类型扫描程序的方法nextString()未定义” 及 线程“main”输入不匹配异常中的“异常” 在throwFor(未知来源) 在下一个(未知源) 在下一个双(未知源)” 这是我的密码:Java帮助用户输入中断While循环,java,while-loop,Java,While Loop,我只是做了一个简单的数学辅导游戏,但我似乎不知道如何用用户输入来打破它。这就是我目前得到的任何帮助都是感激的。我现在知道如何使用.equals比较字符串,但我不断地遇到错误 “类型扫描程序的方法nextString()未定义” 及 线程“main”输入不匹配异常中的“异常” 在throwFor(未知来源) 在下一个(未知源) 在下一个双(未知源)” 这是我的密码: import java.util.Scanner; public class HomeWork{ public sta
import java.util.Scanner;
public class HomeWork{
public static void main(String[] args) {
while (true)
{
Scanner console =new Scanner(System.in);
double correctAnswer;
double userResponse;
String SecondResponse;
String end = "stop";
int n1 = (int)(10 * Math.random() + 1);
int n2 = (int)(10 * Math.random() + 1);
int operator = (int) (4 * Math.random() + 1);
if (operator == 1){
correctAnswer = n1 + n2;
System.out.println("What is " + n1 + " + " + n2 + " ?");
} else if ( operator == 2){
correctAnswer = n1 - n2;
System.out.println("What is " + n1 + " - " + n2 + " ?");
} else if ( operator == 3) {
correctAnswer = n1 * n2;
System.out.println("What is " + n1 + " * " + n2 + " ?");
} else {
correctAnswer = n1 / n2;
System.out.println("What is " + n1 + " / " + n2 + " ?");
}
userResponse = console.nextDouble();
if (userResponse == correctAnswer){
System.out.println("You got the correct answer!");
} else {
System.out.println("Sorry but the correct answer is:" + correctAnswer);
}
SecondResponse = console.nextString();
if(end.equals(SecondResponse))
System.out.println("End of Program");
break;
}
}
}
许多问题:
你最后一次如果。。。缺少{大括号}
因为break语句位于错误的位置,因为只有print语句受if条件的影响
然后:scanner实际上没有方法nextString()。字符串只有next()
不要假设类中存在什么方法。请参考javadoc,尤其是当编译器已经提示您的假设不是基于现实的时候
但我一直在犯错误。“未定义的方法nextString()用于
“类型扫描器”
更改此项:
SecondResponse = console.nextString();
为此:
SecondResponse = console.next();
此外,确保正确打开和关闭支架:
if(end.equals(SecondResponse)) {
System.out.println("End of Program");
break;
}
谢谢你,你是个救生员!欢迎你。