我正在尝试用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.");
}
}
}
2条答案
按热度按时间dgjrabp21#
不能比较string和char,而且应该使用.equals()方法比较input和string.valueof(ranletter),因为
总是假的
ipakzgxi2#
您正在尝试将字符串与字符进行比较:
改为:
以及
input == String.valueOf(ranLetter)
至input.equals(String.valueOf(ranLetter)