SHARE
TWEET

scanner: read until valid

DulcetAirman Mar 11th, 2019 (edited) 72 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package ch.claude_martin;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class SomeClass {
  6.   static Scanner scanner = new Scanner(System.in);
  7.  
  8.   public static void main(String... args) {
  9.     boolean validInput = false;
  10.     int arrayID = -1;
  11.     do {
  12.       System.out.print("Array ID: ");
  13.       try {
  14.         arrayID = scanner.nextInt();
  15.         validInput = true;
  16.       } catch (Exception e) {
  17.         System.out.println("You must enter an ID (decimal numbers only)\nPlease Try Again !");
  18.         scanner.next();
  19.       }
  20.     } while (!validInput);
  21.     System.out.println("ID has been set to: " + arrayID);
  22.   }
  23.  
  24. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top