View difference between Paste ID: Y0bWrrjA and PkNzZfDe
SHOW: | | - or go back to the newest paste.
1
package ch.claude_martin;
2
3
import java.util.Scanner;
4
5
public class SomeClass {
6-
  static Scanner scanner = new Scanner(System.in);
6+
  private static final Scanner SCANNER = new Scanner(System.in);
7
8
  public static void main(String... args) {
9-
    boolean validInput = false;
9+
    var i = readInt("Array ID");
10-
    int arrayID = -1;
10+
    System.out.println("ID has been set to: " + i);
11-
    do {
11+
    System.out.println("End of program.");
12-
      System.out.print("Array ID: ");
12+
13-
      try {
13+
14-
        arrayID = scanner.nextInt();
14+
  /**
15-
        validInput = true;
15+
   * Reads an integer from the standard input.
16-
      } catch (Exception e) {
16+
   * 
17-
        System.out.println("You must enter an ID (decimal numbers only)\nPlease Try Again !");
17+
   * @param description
18-
        scanner.next();
18+
   *          A short description of the input for the user.
19
   */
20-
    } while (!validInput);
20+
  public static int readInt(String description) {
21-
    System.out.println("ID has been set to: " + arrayID);
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
}