当我有int答案= in.nextInt()时怎么办?在第8行中什么都没有出现

所以我没有意识到程序正在运行,只是空白,因为java读取下来了,系统在我看到答案之前一直在等我输入答案。谢谢@wdc的帮助。


原来的


我目前正在练习Java,遇到了一个已解决的问题,但我不明白为什么,当我有这样的程序时,程序如何运行:


import java.util.Scanner;

public class Practice {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);


        int number1 = (int)(System.currentTimeMillis() % 10);

        int number2 = (int)(System.currentTimeMillis() / 10 % 10);




        System.out.print("What is " +  number1 + " + " + number2 + "?");


        int answer = in.nextInt();


        System.out.println(number1 + " + " + number2 + " = " + answer + " is " + (number1 + number2 == answer));



    }


}

但是当我有这样的时候是行不通的:


import java.util.Scanner;

public class Practice {

    public static void main(String[] args) {

            Scanner in = new Scanner(System.in);


            int number1 = (int)(System.currentTimeMillis() % 10);

            int number2 = (int)(System.currentTimeMillis() / 10 % 10);

            int answer = in.nextInt();




            System.out.print("What is " +  number1 + " + " + number2 + "?");



            System.out.println(number1 + " + " + number2 + " = " + answer + " is " + (number1 + number2 == answer));



        }


    }

我想知道,这样我以后就可以避免这个问题。


守候你守候我
浏览 396回答 2
2回答

人到中年有点甜

如果我正确理解了您的问题,则不确定这两种情况下的输出为何不同?请注意,java按照代码中出现的顺序执行语句。所以,当你把int answer = in.nextInt();在之前System.out.print("What is " +  number1 + " + " + number2 + "?");你的程序是等待用户输入,你看不到任何东西印在屏幕上。如果您在控制台中输入内容,然后按Enter键,程序将继续执行,您将看到其余的输出。但是,如果您int answer = in.nextInt();在打印语句之后移动,则将执行第一个打印语句,并且您会在控制台中看到一些输出。

30秒到达战场

好吧,说它不起作用并不是真的正确,因为确实如此。问题是在第二个代码段中,在问题的控制台打印之前,您具有阻止方法“ in.nextInt()”,因此仅在遇到问题后才需要让他回答。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java