我试图以两个不同的整数形式输入输入,这些整数用空格ex 14 2
分隔。
如果输入是double而不是int,一个字符,或者基本上不是由空格分隔的两个整数,我找不到提示用户再次尝试的方法。
我真的不想使用exceptions and try/catch
语句,因为我不理解它们。
我宁愿接受字符串[] arr并使用split(“”)或只做console.nextInt();
。任何反馈都会很棒。我知道它不漂亮。
Scanner console = new Scanner(System.in);
boolean ok = true;
boolean ok2 = true;
while (ok = true){
for(int i = 0; i<=2; i++){
if(!console.hasNextInt()){
kb.next();
System.out.println("Bad input, try again");
ok2 false;
}
else if(i = 0 && ok2 = true){
int a = console.hasNextInt();
}
else if(i = 1 && ok2 = true){
int b = console.hasNextInt();
ok = false; //means there are two #s and the program can continue with a and b
}
else{
}
}
答案 0 :(得分:1)
以下代码接受输入,直到只获得正数。否定与零数字由while循环条件处理。在另一个while循环条件下使用!sc.hasNextInt()
处理字符。
Scanner sc = new Scanner(System.in);
int number;
do {
System.out.println("Please enter a positive number : ");
while (!sc.hasNextInt()) {
System.out.println("That is not a valid number.");
sc.next();
}
number = sc.nextInt();
} while (number <= 0);
System.out.println("Recieved a Positive number = " + number+". Thanks!");
输出 -
Please enter a positive number :
-1
Please enter a positive number :
0
Please enter a positive number :
n
That is not a valid number.
6
Recieved a Positive number = 6. Thanks!
答案 1 :(得分:1)
我正在努力编写尽可能简单易用的代码,
Scanner console = new Scanner(System.in);
System.out.print("Enter two numbers ");
String str = console.readLine();
String values[] = str.split(" ");
int n1, n2;
try{
n1 = Integer.parseInt(values[0]);
//Convert first String value to int, if it will be anything else than int
// then it will throw the NumberFormatException
}catch(NumberFormatException e){
System.out.println("First number is not integer");
}
try{
n2 = Integer.parseInt(values[1]);
//Convert second String value to int, if it will be anything else than int
// then it will throw the NumberFormatException
}catch(NumberFormatException e){
System.out.println("Second number is not integer");
}
注意强>
此代码基于以下假设:仅用户输入的两个元素。不超过两个。在这种情况下,需要更改代码。
答案 2 :(得分:1)
使用Scanner#hasNextInt()验证输入的另一种解决方案:
final Scanner console = new Scanner(System.in);
final List<Integer> input = new ArrayList<Integer>();
while (true)
{
System.out.print("Please enter an integer : ");
if (console.hasNextInt())
{
input.add(console.nextInt());
}
else
{
System.out.println("Bad input, try again ...");
console.next();
}
if (input.size() >= 2)
{
break;
}
}
System.out.println("\n");
System.out.println("First integer entered was : " + input.get(0));
System.out.println("Second integer entered was : " + input.get(1));