For my review
If there is "Enter 0 to 2", "Enter 0 to 2" is displayed. If there is "Enter character string", "Not an integer value" is displayed.
Because I could use the Scanner hasNext instead of using try-catch Record that there is such a way.
hello.java
void getJudgeHand() {
while (true) {
System.out.println("command? 0:Goo 1:Par 2:Choki");
if (scanner.hasNextInt()) {
myHand = scanner.nextInt();
if (myHand >= 0 && myHand <= 2) break;
}
else {
scanner.next();
System.out.println("Not an integer value");
}
System.out.println("Please enter from 0 to 2");
}
}
Try-catch method
hello.java
void getJudgeHand() {
while (true) {
try {
System.out.println("command? 0:Goo 1:Par 2:Choki");
this.myHand = scanner.nextInt();
if (this.myHand <= 2 && this.myHand >= 0) { //Break if 2 or less and 0 or more
break;
}
} catch (InputMismatchException e) {
System.out.println("Not an integer value");
scanner.next(); //Discard the input
}
System.out.println("Please enter from 0 to 2");
}
}
Recommended Posts