重用Java扫描器
我写了一个小的Java代码来计算用户使用Scanner输入的两个整数的乘积。用户被迫输入整数值。代码如下所示重用Java扫描器,java,loops,input,integer,Java,Loops,Input,Integer,我写了一个小的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
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);
}
}
第一个数字的循环工作正常。但是,第二个不是:如果用户输入的不是整数值,则消息“not valid.second number:”将显示两次第一个号码:
g
无效。第一个号码:
2
第二个号码:
f
无效。第二个号码:
无效。第二个号码:
4
2*4=8
这种行为的原因是什么?我想我做错了什么事。
我曾尝试使用两个不同的扫描仪(每个数字一个),问题消失了,但我不认为创建大量实例是正确的途径。
有人能帮忙吗
谢谢。因为即使接受了第一个int值,仍然有换行符要使用 所以换成
x=sc.nextInt();
sc.nextLine();
或重新初始化扫描仪,如:x=sc.nextInt();sc=新扫描仪(系统英寸)@RohitJain根据OP,我试着使用两种不同的扫描仪(每个数字一个)来解决这个问题dissapears@ScaryWombat完美的它工作得很好!所以这是不是就像我在读一行中的字符,但我留下了“\n”,然后sc.nextLine()读“\n”?@ScaryWombat顺便说一句:我试着给你的答案加1分,但由于我的名声不好,没有效果:(再次感谢。感谢@Krippulo