我将如何使用Scanner进行简单的if-else语句作为键盘输入,将整数与参数进行比较,如果不是期望的结果,则再次提示用户再次输入该整数?这就是我所拥有的,我认为这应该很容易,但是我只是在学习;
public static void main(String[] args) {
Scanner myInt = new Scanner(System.in);
System.out.println("Enter a number between 1 and 10");
int choice = myInt.nextInt();
if (choice <= 10) {
System.out.println("acceptable");
} else {
System.out.println("unacceptable");
System.out.println("Enter a number between 1 and 10");
}
}
}
有关我应该如何处理此问题的任何提示?
谢谢!
答案 0 :(得分:3)
您可以使用while循环不断询问数字并检查数字是否可接受:
public static void main(String[] args) {
Scanner myInt = new Scanner(System.in);
boolean acceptable=false;
while(!acceptable){
System.out.println("Enter a number between 1 and 10");
int choice = myInt.nextInt();
if (choice <= 10 && choice>=1) {
System.out.println("acceptable");
acceptable=true;
} else {
System.out.println("unacceptable");
}
}
}
答案 1 :(得分:-1)
public static void main(String[] args) {
// TODO Auto-generated method stub
while (true) {
if (insertNumber()) {
break;
}
}
}
public static boolean insertNumber() {
System.out.println("Enter a number between 1 and 10");
Scanner myInt = new Scanner(System.in);
int choice = myInt.nextInt();
if (choice <= 10) {
System.out.println("acceptable");
return true;
} else {
System.out.println("unacceptable");
return false;
}
}