Java:代码未按正确方式运行

标签 java warnings

首先你必须知道我是 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/

相关文章:

java - 为什么在 java src 中 Integer 类的 toString 方法中使用负 int 进行 mod 操作

java - FindBugs IntelliJ 和 Maven 中的匹配错误级别

java - Netty的WebSocket消息是否被压缩?

java - 在移动设备上找不到 sqlite db,但可以在模拟器上运行

c# - Visual Studio 缺少警告

c - 如何解决错误 "assignment makes integer from pointer without a cast"?

java - Eclipse 中无用的烦人警告

java - vertxexecute阻止不同的行为

c++ - 警告 : conversion to 'unsigned char' from 'int' may alter its value

c++ - 如何正确声明模板类的嵌套类的友元?