终端中的“无与伦比的类型:java.lang.String和int”

时间:2012-11-16 23:27:52

标签: java terminal while-loop

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

首先我将TerminalIO.KeyboardReader更改为java.util.Scanner,现在当我通过Terminal运行它时,它返回“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.");

}

}

2 个答案:

答案 0 :(得分: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");
}

答案 1 :(得分:1)

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

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

       while (!(x.equals(Integer.toString(randomNumber)))) {