我正在尝试在Java中创建字母拼音,但是我的while循环无法正常工作。我得到的错误是
错误:二进制运算符'!='的错误操作数类型
while(输入!= ranLetter){
^
第一种类型:字符串
第二种类型:字符
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.");
    }
  }
}

最佳答案

您正在尝试将String与char进行比较:

while (input != ranLetter)
改为:
 while (!input.equals(String.valueOf(ranLetter)))
以及input == String.valueOf(ranLetter)input.equals(String.valueOf(ranLetter)

10-08 09:19