Search code examples
javainputstdin

User prompt is one line off for some reason?


I'm asking for user input, but I want it to follow the enter: prompt and be on the same line.

My code produces this as a result input from 'ok'

ok
enter: ok
ok

I would like the user input to start after enter: - hoping for this as a result...

enter: ok
ok

Here's my code:

private static Scanner u = new Scanner(System.in);
  try{
      while(u.hasNext() && !u.equals("exit")) {
          System.out.printf("enter: ");
          usrInput = u.next();
          System.out.printf(usrInput + "\n");
          System.out.println(findClosestMatch(usrInput.toLowerCase()));
        }
      } catch(NullPointerException e) {
            System.out.println("Error - NullPointerException");
      }

Solution

  • u.hasNext() is blocking on input before the prompt. It's unnecessary, since calling u.next() afterwards will block anyway. And you're comparing the actual Scanner object to "exit", which will never be true. Try this:

    while (true) {
        System.out.print("enter: ");
        if (!u.hasNext() || (usrInput = u.next()).equals("exit")) {
            break;
        }
        System.out.println(usrInput);
        System.out.println(findClosestMatch(usrInput.toLowerCase()));
    }