首先你必须知道我是 Java 菜鸟,我刚刚开始编码,这是我的第一种编程语言。所以,如果我开始有点愚蠢,请不要生气,我只是想学习编码 - 谢谢
我正在尝试制作一个简单的“猜谜游戏”,但我的代码没有等待用户输入。 请帮助我,我不知道该怎么办。
我的代码:
public static void main(String[] args)
{
//Creating the scanner
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//Creating the two random numbers.
Random rand = new Random();
int userNumber = rand.nextInt(10) + 1;
int comNumber = rand.nextInt(10) + 1;
//Asks the user what to do.
System.out.println("Your number is: " + userNumber +" of 10");
System.out.println("Do you think that your number is Heigher(H), Lower(L) or Equal To(E) the computers number");
//Checking if the user is right.
//If the user types in LOWER
if(userNumber < comNumber && input.equals("L"))
System.out.println("You are right. The computer's number is: " + comNumber);
if(userNumber < comNumber && !input.equals("L"))
System.out.println("You are wrong. The computer's number is: " + comNumber);
//If the user types in EQUAL TO.
if(userNumber == comNumber && input.equals("E"))
System.out.println("You are right. The computer's number is: " + comNumber);
if(userNumber == comNumber && !input.equals("E"))
System.out.println("You are wrong. The computer's number is: " + comNumber);
//If the user types in HEIGHER.
if(userNumber > comNumber && input.equals("H"))
System.out.println("You are right. The computer's number is: " + comNumber);
if(userNumber > comNumber && !input.equals("H"))
System.out.println("You are wrong. The computer's number is: " + comNumber);
else
System.out.println("You can only type in ' L ', ' E ' or ' H '.");
}
}
如果您能帮助我解决问题,并告诉我如何删除 @SuppressWarnings("resource")/解释为什么它必须在那里,我会很高兴。
最佳答案
您使用的扫描仪
是错误的。您需要调用scanner.nextLine()
要从用户获取输入(字符串),您需要将字符串转换为整数(使用 Integer.parseInt
)以将其与其他整数进行比较。
关于Java:代码未按正确方式运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21292329/