为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

守候你守候我 2021-05-06 18:34:54
所以我没有意识到程序正在运行,只是空白,因为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));        }    }我想知道,这样我以后就可以避免这个问题。
查看完整描述

2 回答

?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

如果我正确理解了您的问题,则不确定这两种情况下的输出为何不同?

请注意,java按照代码中出现的顺序执行语句。所以,

当你把int answer = in.nextInt();在之前System.out.print("What is " +  number1 + " + " + number2 + "?");你的程序是等待用户输入,你看不到任何东西印在屏幕上。如果您在控制台中输入内容,然后按Enter键,程序将继续执行,您将看到其余的输出。

但是,如果您int answer = in.nextInt();在打印语句之后移动,则将执行第一个打印语句,并且您会在控制台中看到一些输出。


查看完整回答
反对 回复 2021-05-19
?
30秒到达战场

TA贡献1828条经验 获得超6个赞

好吧,说它不起作用并不是真的正确,因为确实如此。问题是在第二个代码段中,在问题的控制台打印之前,您具有阻止方法“ in.nextInt()”,因此仅在遇到问题后才需要让他回答。


查看完整回答
反对 回复 2021-05-19
  • 2 回答
  • 0 关注
  • 395 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信