Java check input is integer or empty to allow for default value

Robbie Avill :

I'm currently trying to make a fairly basic java program that asks users for input and if they hit enter to provide a default value.

At the moment my code to do this is

System.out.println("Please enter a port number (default 8080): ")
port = scanner.nextLine();
      if (port.isEmpty() || port.equals("8080")) {
          port = "8080";
          System.out.println("Using default port...");
      }
      else {
          System.out.println("Using new port...");
      }

I would like to alter this to check that the input (if there is any) is an integer and if not, loop back round to ask for input again. I know it needs to use a combination of hasNextInt and nextLine but I cannot figure it out.

Any help would be appreciated.

Joakim Danielson :

Instead of messing around with nextInt() I would suggest trying to parse the input as an integer and handle the exception if it fails

Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a port number (default 8080): ");
String port = null;
while (true) {
    port = scanner.nextLine();
    if (port.isEmpty() || port.equals("8080")) {
        port = "8080";
        break;
    } else {
        try {
            Integer.valueOf(port);
            break;
        } catch (NumberFormatException ex) {
            System.out.println("Incorrect value given, try again");
        }
    }
}
System.out.println("You have selected " + port);
scanner.close();

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=379938&siteId=1