我编写了一段简短的 Java 代码来计算用户使用 Scanner 输入的两个整数的乘积。用户被迫输入整数值。代码如下所示。
import java.util.Scanner;
public class Principal {
public static void main(String[] args) {
int x=0,y=0;
Scanner sc=new Scanner(System.in);
//Asks for the first number until the user inputs an integer
System.out.println("First number:");
while(!sc.hasNextInt()){
System.out.println("Not valid. First number:");
sc.nextLine();
}
x=sc.nextInt();
//Asks for the second number until the user inputs an integer
System.out.println("Second number:");
while(!sc.hasNextInt()){
System.out.println("Not valid. Second number:");
sc.nextLine();
}
y=sc.nextInt();
//Show result
System.out.println(x+"*"+y+"="+x*y);
}
}
第一个数字的循环工作正常。但是,第二个则不然:如果用户输入的内容不是整数值,则消息“无效。第二个数字:”会显示两次!
第一个数字:
克
无效。第一个数字:
2
第二个数字:
f
无效。第二个数字:
无效。第二个数字:
4
2*4=8
这种行为的原因是什么?我想我做错了什么。
我尝试使用两个不同的扫描仪(每个数字一个),问题就消失了,但我不认为创建大量实例是正确的路径。
有人可以帮忙吗?
谢谢。
最佳答案
因为即使在接受第一个 int 值之后,仍然需要使用换行符,
所以改为
x=sc.nextInt();
sc.nextLine();
关于java - 重用 Java 扫描器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59675833/