Advertisement
Guest User

Untitled

a guest
Mar 4th, 2015
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.99 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Scanner;
  3.  
  4.  
  5.  
  6. public class Test {
  7.     public static void main(String[] args) {
  8.         // Creating an array with the allowed int values
  9.         ArrayList<Integer> allowedValues = new ArrayList<Integer>();
  10.         allowedValues.add(0);
  11.         allowedValues.add(1);
  12.         allowedValues.add(2);
  13.         allowedValues.add(3);
  14.        
  15.         Scanner scan = new Scanner(System.in);
  16.         // Declaring chosenInt (your selection) outside while loop so it can be used outside of the while loop.
  17.         int chosenInt;
  18.         // !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.
  19.         // !allowedValues.contains checks if the value sent to the method is in the arraylist, and inverses the value.
  20.         while(!scan.hasNextInt() || !allowedValues.contains((chosenInt = scan.nextInt()))) {
  21.             scan.nextLine();
  22.             System.out.println("Incorrect input, want a number between 0 and 3");
  23.         }
  24.         System.out.println(chosenInt);
  25.     }
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement