【Java】数値チェックなどを行いながら標準入力を受け取る
1
while(true) {
//数値チェック
while(true) {
if(sc.hasNextInt()) {
a = sc.nextInt();
break;
}else {
System.out.println("再度数値を入力してください");
sc.next();
}
}
//条件チェック
if(a >= 0) {
break;
}else {
System.out.println("再度数値を入力してください");
}
}
2(ボツ)
public static int check(Scanner sc) {
int a = 0;
while (true) {
//数値チェック&条件チェック(不可)
if (sc.hasNextInt() && a >= 0) {
a = sc.nextInt();
System.out.println("入力された数値は:" + a);
break;
} else {
System.out.println("再度数値を入力してください");
sc.next();
}
}
return a;
}
こっちの方がいいよ!などあればお願いします!
3(@shiracamusさんにより実践的なコードを教えていただきました)
import java.util.Scanner;
import java.util.function.Function;
public class ValidatingInput {
//(個人メモ)Function<T, R>の抽象メソッド。Integer型の引数を受け取って、 Boolean型の値を返す。
public static int inputInteger(Scanner sc, Function<Integer, Boolean> isValid) {
while (true) {
System.out.print("数値を入力してください: ");
System.out.flush();
if (sc.hasNextInt()) {
int value = sc.nextInt();
//(個人メモ)受け取ったisValidによって条件チェック
if (isValid.apply(value)) {
return value;
}
System.out.println("範囲外の数値です。");
} else {
System.out.println("数値ではありません。");
sc.next();
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//(個人メモ)条件を引数として渡す
int a = inputInteger(sc, value -> value >= 0);
System.out.println("入力された数値は:" + a);
}
}
コメントは全て、後から個人的なメモとして書き足したものになります。
Function<T, R>
apply(T)
に触れるのは初めてでしたが、「java.util.function以下の関数インターフェース使い方メモ」を参考に理解することができました。
shiracamusさん、ありがとうございます。