Java:代码工作不正确 [英] Java: Code ain't working the right way
本文介绍了Java:代码工作不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
首先,您必须知道我是 Java 的菜鸟,我刚开始编写代码,它是我的第一门编程语言.所以如果我开始有点愚蠢,请不要生气,我只是想学习编码 - 谢谢
我正在尝试制作一个简单的猜谜游戏",但我的代码没有等待用户输入.请帮帮我,我不知道该怎么办.
I'm trying to make a simple " guessing game ", but my code aren't waiting for the user-input. please help me, I don't know what to do.
我的代码:
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
是错误的.您需要调用 scanner.nextLine()
从用户那里获取输入(一个字符串),你需要将字符串转换为整数(使用 Integer.parseInt
) 进行比较它与其他整数.
You're using Scanner
wrong. You need to call scanner.nextLine()
to get input (a String) from the user, and you need to convert the String to an integer (with Integer.parseInt
) to compare it with other ints.
这篇关于Java:代码工作不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文