while循环不工作错误:二进制运算符“!=”的操作数类型错误java

wfveoks0  于 2021-07-07  发布在  Java
关注(0)|答案(2)|浏览(675)

我正在尝试用java制作一个字母gusser,但是我的while循环不起作用。我得到的错误是
错误:二进制运算符“!=”的操作数类型错误while(输入!=ranletter){^第一种类型:string第二种类型:char 1错误。
我试图将ranletter转换为char,但循环从未停止。
这是我的密码:

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int ranNum = (int)(Math.random()*26 + 97);
    char ranLetter = (char)ranNum;
    //This is just for testing
    System.out.println(ranLetter);

    String input = in.nextLine();
    if (input == String.valueOf(ranLetter)){
      System.out.println("FIRST TRY BTW!! the letter was " + ranLetter + ".");
    }

    else{
      int counter = 0;
      while (input != ranLetter){
        System.out.println("Nope :( try again.");
        counter += 1;
        input = in.nextLine();
      }
      System.out.println("Nice you got it. The letter was " + ranLetter + ". It took you " + String.valueOf(counter) + " guesses.");
    }
  }
}
dgjrabp2

dgjrabp21#

不能比较string和char,而且应该使用.equals()方法比较input和string.valueof(ranletter),因为

"A" == String.valueOf('A')

总是假的

ipakzgxi

ipakzgxi2#

您正在尝试将字符串与字符进行比较:

while (input != ranLetter)

改为:

while (!input.equals(String.valueOf(ranLetter)))

以及 input == String.valueOf(ranLetter)input.equals(String.valueOf(ranLetter)

相关问题