为什么当我输入错误的答案时,我无法得到错误的输出

时间:2015-09-15 02:55:51

标签: java math

public static void main(String[] args) {
    Scanner Keyboard = new Scanner(System.in);
    System.out.println("Enter your name: ");
    String firstname =Keyboard.nextLine();
    System.out.println("Welcome "+ firstname+  "!"+ " Please answer the following questions:");
    int x =  (int)(20 * Math.random()) + 1;
    int y =  (int)(20 * Math.random()) + 1;
    int sum = (x+y);
    System.out.println(x + " + " + y + " = ");
    String answer =Keyboard.nextLine();
    if (sum == (x+y)){
    System.out.println("Correct!");
    }else if(sum != (x+y))
    System.out.println("Wrong!");

我必须做一个简短的测验,但我不能让输出说错。我可以说它是正确的,但没有错。

1 个答案:

答案 0 :(得分:1)

由于您指定sum,因此

x+y始终等于int sum = (x+y);。 您可能希望将answer解析为int并检查它是否等于answer

if (sum == Integer.parseInt(answer)) {
    System.out.println("Correct!");
} else {
    System.out.println("Wrong!");
}