0

我在学校编写了一个简单的 Java 程序来猜测正确答案,当我把它带回家时,它遇到了错误。

起初我将 TerminalIO.KeyboardReader 更改为 java.util.Scanner,现在当我通过终端运行它时,它返回“Incomparable types: java.lang.String and int”。

有什么帮助吗?真的很迷茫。

代码:

import java.util.Scanner;

import java.util.Random;

public class guess { 

       public static void main(String [] args) {
           Scanner keyboard = new Scanner(System.in);
           Random generator = new Random();
           System.out.println("I am thinking of a number from 1 to 10.");
           System.out.println("You must guess what it is.");
           System.out.print("Enter a guess: ");
           int randomNumber = generator.nextInt(10) + 1;
           String x = keyboard.nextLine();
           int guessNum = 1;
           while (x != randomNumber) {
                  System.out.println("Guess again!");
                  x = keyboard.nextLine();
                  guessNum ++;
                }
                System.out.println("RIGHT!");
                System.out.println("You got it correct in " +guessNum + " guesses.");

}

}

4

2 回答 2

5

您无法比较 int 和 String。

你可以这样做:

int someInt = 6;
String someString = "6";
String intAsString = Integer.toString(someInt);

if (someString.equals(intAsString)) {
    System.out.println("Yay");
}

您可以像这样将字符串转换为数字:

int someInt = 6;
String someString = "6";
try {
    int stringAsInt = Integer.parseInt(someString);
    if (stringAsInt == someInt) {
        System.out.println("Yay");
    }
}
catch (NumberFormatException nfe) {
    System.out.println("String is not an integer");
}
于 2012-11-16T23:30:44.127 回答
1

您正在将 String 与 int 进行比较(它们是不兼容的类型)

将您的 int 转换为字符串并进行比较

       while (!(x.equals(Integer.toString(randomNumber)))) {
于 2012-11-16T23:30:23.787 回答