Reputation: 41
How would I take a simple if-else statement using a Scanner for keyboard input, compare an integer against an argument and re prompt the user to input the integer again if it is not the desired result? Here is what I have, I think this should be fairly easy but I'm only learning;
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");
}
}
}
Any tips on how I should approach this?
Thanks!
Upvotes: 0
Views: 509
Reputation: 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;
}
}
Upvotes: -1
Reputation: 531
You could use a while loop to keep asking for numbers and checking if they are acceptable:
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");
}
}
}
Upvotes: 4