javaBob69
javaBob69

Reputation: 11

Scanner always requires two inputs (Java)

I am trying to implement a method that let's a player chose a username. The method suggests one based on the username of the currently running OS. Now I want to give the user the option to change his/her nickname, if he/she is not content with the suggestion. The problem now is, that I always have to enter my statement twice, as I guess either one is not being taken in.

(e.g. I have to enter:

"y"

"y")

I've tried altering the statement in the while loops (e.g. "nameChange.hasNextLine()"). I've tried to add "nameChange.nextLine();" befor and after "line = nameChange.nextLine();" (as a similar post on SO suggested) but neither worked.

public class SetUsername implements Runnable {

    /**
     * Suggests a name based on the accessing OS's user Let's the user change the suggestion to his
     * or her own username.
     */
    @Override
    public void run() {
      String name = System.getProperty("user.name");
      Scanner nameChange = new Scanner(System.in);
      System.out.println("Your username is: " + name + ". Would you like to change it? (y/n)");
      String line;
      while (true) {
        line = nameChange.nextLine();
        if (line.equals("y")) {
          System.out.println("Chose a new username:");
          while(true) {
            name = nameChange.nextLine();
            System.out.println("Your new username is "+ name);
            break;
          }
          break;
        } else if (line.equals("n")) {
          break;
        } else {
          System.out.println("Invalid input. Your username is: " + name + ". "
              + "Would you like to change it? (y/n)");
        }
      }
      send(Command.SET_USERNAME, name);
    }
  }


Upvotes: 0

Views: 55

Answers (1)

javaBob69
javaBob69

Reputation: 11

"You probably have some other method running before ending with a call to next() or nextInt(), and thus not consuming the line ending." – JB Nizet

That was the problem.

Upvotes: 1

Related Questions