1
while(true) {
//Numerical check
while(true) {
if(sc.hasNextInt()) {
a = sc.nextInt();
break;
}else {
System.out.println("Please enter the number again");
sc.next();
}
}
//Condition check
if(a >= 0) {
break;
}else {
System.out.println("Please enter the number again");
}
}
public static int check(Scanner sc) {
int a = 0;
while (true) {
//Numerical check & condition check(Impossible)
if (sc.hasNextInt() && a >= 0) {
a = sc.nextInt();
System.out.println("The entered number is:" + a);
break;
} else {
System.out.println("Please enter the number again");
sc.next();
}
}
return a;
}
This one is better! If you have any, please!
import java.util.Scanner;
import java.util.function.Function;
public class ValidatingInput {
//(Personal notes)Function<T, R>Abstract method. Takes an Integer type argument and returns a Boolean type value.
public static int inputInteger(Scanner sc, Function<Integer, Boolean> isValid) {
while (true) {
System.out.print("Please enter a number: ");
System.out.flush();
if (sc.hasNextInt()) {
int value = sc.nextInt();
//(Personal notes)Condition check by received isValid
if (isValid.apply(value)) {
return value;
}
System.out.println("It is a number outside the range.");
} else {
System.out.println("It is not a numerical value.");
sc.next();
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//(Personal notes)Pass the condition as an argument
int a = inputInteger(sc, value -> value >= 0);
System.out.println("The entered number is:" + a);
}
}
All comments will be added later as personal notes.
Function<T, R> apply(T)It was my first time to touch, but "[java.util.function The following function interface usage memo](https://qiita.com/opengl-8080/items/22c4405a38127ed86a31)I was able to understand it with reference to.
Thank you, shiracamus.
Recommended Posts