我刚刚做了一个简单的数学导师游戏,但我似乎无法弄清楚如何用用户输入打破它。这是我到目前为止得到的任何帮助表示赞赏。谢谢。 hmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm
import java.util.Scanner;
public class HomeWork{
public static void main(String[] args) {
while (true)
{
Scanner console =new Scanner(System.in); // create object for input
double correctAnswer;
double userResponse;
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);
}
if(end = console.nextString()){
break;
}
}
}
}
答案 0 :(得分:1)
您不能使用=
运算符(用于为变量赋值)来比较字符串值,而是需要使用equals()
方法来比较字符串,如下所示:
if(end.equals(console.nextString())){
break;
}
另外,请注意,您甚至无法使用==
运算符来比较字符串值,即您只能使用.equals()
,如上所示。