DulcetAirman icon

Scanner readInt in loop

DulcetAirman | PRO | 03/11/19 10:42:39 PM UTC | 0 ⭐ | 661 👁️ | Never ⏰ | []
Java |

900 B

|

None

|

0 👍

/

0 👎

package ch.claude_martin;
 
import java.util.Scanner;
 
public class SomeClass {
  private static final Scanner SCANNER = new Scanner(System.in);
 
  public static void main(String... args) {
    var i = readInt("Array ID");
    System.out.println("ID has been set to: " + i);
    System.out.println("End of program.");
  }
 
  /**
   * Reads an integer from the standard input.
   * 
   * @param description
   *          A short description of the input for the user.
   */
  public static int readInt(String description) {
    while (true) {
      System.out.print(description);
      System.out.print(": ");
      System.out.flush();
      if (SCANNER.hasNextInt()) {
        return SCANNER.nextInt();
      } else {
        System.out.println("You must enter an integer (decimal numbers only)");
        System.out.println("Please Try Again !");
        SCANNER.next();
      }
    }
  }
}

Comments