“二元运算符的错误操作数类型”和“无法比较的类型:char和Random”错误

时间:2015-08-20 07:46:20

标签: java

这个程序应该是一个猜谜游戏,你在a和j之间输入一个字母,并尝试猜测随机选择的答案。 我一直收到有关if语句的错误消息。 对于那些<或>,它表示“错误:二元运算符的错误操作数类型”。 对于带有==或!=的那些,它表示错误:无法比较的类型:char和Random。 我该怎么做才能解决这个问题?

import java.util.Scanner;
import java.lang.Math;
import java.util.Random;

class Guess{

    public static void main( String[] args ){

    Scanner sc = new Scanner(System.in);

    System.out.println("I'm thinking of a letter in the range a to j. You have three guesses. ");

    System.out.print("Enter your first guess: ");

    Random r = new Random();
    char i = (char)(r.nextInt(10) + 'a');

    if(i>r){
        System.out.println("Your guess is too high. ");

    } else if(i<r){
        System.out.println("Your guess is too low. ");

    } else if(i==r){
        System.out.println("You win! ");

    }

    System.out.print("Enter your second guess: ");

    i = (char)(r.nextInt(10) + 'a');

    if(i>r){
        System.out.println("Your guess is too high. ");

    } else if(i<r){
        System.out.println("Your guess is too low. ");

    } else if(i==r){
        System.out.println("You win! ");

        }

    System.out.print("Enter your third guess: ");

    i = (char)(r.nextInt(10) + 'a');

    if(i>r){
        System.out.println("Your guess is too high. ");

    } else if(i<r){
        System.out.println("Your guess is too low. ");

    } else if(i==r){
        System.out.println("You win! ");

        }

    if(i!=r){
        System.out.println("You lose. The letter was " +r+ ".");
    }

    }
}

1 个答案:

答案 0 :(得分:0)

char是基本类型,Random是引用类型。您无法使用&lt ;,&gt;,==或!=运算符自由比较它们。

从我在您的代码中看到的内容,您实际上从未获得用户的输入。您应该使用扫描仪从标准输入读取并将读取值与i进行比较。