我被困在这个循环中。 它是关于得到一个输入(int)n =数字所以我们需要hasNextInt(),这个输入也需要在2到10之间。
import java.util.Scanner;
public class GetNumber {
public static void main(String[] args) {
//kb = keyboard
Scanner kb = new Scanner(System.in);
boolean out = true;
//n = number
int n = 0;
//loop
while (out) {
System.out.println("Enter a number between 2 and 10.");
if (kb.hasNextInt()) {
n = kb.nextInt();
if ((n >= 2 && n <= 10)) {
out = false;
} else {
System.out.println("Please a number between 2 and 10.");
kb.next();
}
out = false;
} else {
System.out.println("Enter a number!");
kb.next();
}
}
out = true;
}
}
答案 0 :(得分:1)
final Scanner kb = new Scanner(System.in);
Integer temp = null;
while (temp == null) {
System.out.println("Enter a number between 2 and 10.");
final String input = kb.nextLine();
try {
final Integer value = Integer.valueOf(input);
if (value >= 2 && value < 10) {
temp = value;
} else {
System.out.println("Bad number, try again");
}
} catch (NumberFormatException ex) {
System.out.println("Not a number, try again");
}
}
int n = temp;
这与@Antoniossss答案类似,但它处理一些边缘情况(非数字输入)。它使用临时值来保存结果,并使用一个名为value的Integer来保存值,同时验证它。
答案 1 :(得分:0)
这更简单
public static void main (String[]args){
//kb = keyboard
Scanner kb = new Scanner(System.in);
int n = 0;
//loop
do{
System.out.println("Enter a number between 2 and 10.");
n=kb.nextInt();
}while(n<2 || n>10);
System.out.println("Nice, you selected "+n);
}
答案 2 :(得分:0)
我也试过了这个。
do {
System.out.print("Choose a number between[2-10]");
while(!kb.hasNextInt()){
kb.nextLine();
System.out.println("It's not a valid number.");
}
n = kb.nextInt();
} while ((v<=1 || v>=11));
答案 3 :(得分:0)
尝试摆脱冗余代码,并使用Do-while循环测试身体并具有类似
的控件do
{
if(n>=2&&n<=10)
{
...
out = true;
}
else
}
out = false;
...
}
}
while(!out);
这应该更好地测试它。