[Java] Receive standard input while performing numerical checks, etc.

[Java] Receive standard input while performing numerical checks, etc.

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");
	}
}

2 (bot)


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!

3 (@shiracamus gave me a practical code)


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

[Java] Receive standard input while performing numerical checks, etc.
[Java] How to receive numerical data separated by spaces in standard input
Read standard input in Java
Story of paiza.jp [Java standard input solution]
Receive joystick input in Java LW JFL
[Java] How to get and output standard input
[ruby] How to receive values from standard input?