SHARE
TWEET

Scanner readInt in loop

DulcetAirman Mar 11th, 2019 60 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.   private static final Scanner SCANNER = new Scanner(System.in);
  7.  
  8.   public static void main(String... args) {
  9.     var i = readInt("Array ID");
  10.     System.out.println("ID has been set to: " + i);
  11.     System.out.println("End of program.");
  12.   }
  13.  
  14.   /**
  15.    * Reads an integer from the standard input.
  16.    *
  17.    * @param description
  18.    *          A short description of the input for the user.
  19.    */
  20.   public static int readInt(String description) {
  21.     while (true) {
  22.       System.out.print(description);
  23.       System.out.print(": ");
  24.       System.out.flush();
  25.       if (SCANNER.hasNextInt()) {
  26.         return SCANNER.nextInt();
  27.       } else {
  28.         System.out.println("You must enter an integer (decimal numbers only)");
  29.         System.out.println("Please Try Again !");
  30.         SCANNER.next();
  31.       }
  32.     }
  33.   }
  34. }
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