Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Scanner;
- public class Test {
- public static void main(String[] args) {
- // Creating an array with the allowed int values
- ArrayList<Integer> allowedValues = new ArrayList<Integer>();
- allowedValues.add(0);
- allowedValues.add(1);
- allowedValues.add(2);
- allowedValues.add(3);
- Scanner scan = new Scanner(System.in);
- // Declaring chosenInt (your selection) outside while loop so it can be used outside of the while loop.
- int chosenInt;
- // !scan.hasNextInt() checks if the next input to the scanner is an int, and the ! inverses the value, so true will be false and false will be true.
- // !allowedValues.contains checks if the value sent to the method is in the arraylist, and inverses the value.
- while(!scan.hasNextInt() || !allowedValues.contains((chosenInt = scan.nextInt()))) {
- scan.nextLine();
- System.out.println("Incorrect input, want a number between 0 and 3");
- }
- System.out.println(chosenInt);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement