1

I have this code...

import java.util.*;

public class SwitchExample {

    public static void main(String[] args) {
        System.out.print("Enter ID: ");
        Scanner scanner = new Scanner(System.in);
        while (!scanner.hasNextInt()) {
            System.out.print("Invalid. Enter again: ");
            scanner.next();
        }

        int number = scanner.nextInt();

        System.out.println("Your number was: " + number);
        System.out.println("Test message got printed!");
    }

}

Typing a valid input is fine, and upon typing an invalid character, it still works as required. However, upon typing an enter key, in either case does not raise an error. Please help on how I can achieve that. I have tried multiple ways but none have worked.

Harry
  • 21
  • 4

2 Answers2

1

Well, you are just scanning integers try alto to scan "Next Line"

while(scanner.hasNextLine()) 

that will catch if you press enter, i assume so.

coder Tester
  • 145
  • 10
1

For enter, you'll need to add a special case, something like that

String line = scanner.nextLine();
if (line .isEmpty()) {
        System.out.println("Enter Key pressed");
}

Here is the full source code for your need:

public static void main(String[] args) {
    System.out.print("Enter ID: ");
    Scanner scanner = new Scanner(System.in);
    String readString = scanner.nextLine();
    while(readString!=null) {
        System.out.println(readString);

        if (readString.isEmpty()) {
            System.out.println("Read Enter Key.");
        }
        else if (isInteger(readString)) {
            System.out.println("Read integer");
        }
        else{
            System.out.println("Read char");
        }

        if (scanner.hasNextLine()) {
            readString = scanner.nextLine();
        } else {
            readString = null;
        }
    }
}

public static boolean isInteger(String s) {
    Scanner sc = new Scanner(s.trim());
    if(!sc.hasNextInt()) return false;
    // we know it starts with a valid int, now make sure
    // there's nothing left!
    sc.nextInt();
    return !sc.hasNext();
}
alain.janinm
  • 19,951
  • 10
  • 65
  • 112