0

I had problem where nextLine was ignoring user input. After some research, I found that I have to clear the Scanner using in.nextLine(), but can you tell me why? I would like to know what I'm doing when I use this:

String edit = in.nextLine();

switch (edit) {
    case "name":
        System.out.println("Enter new name for " + items.get((editItem - 1)).getName());
        String newName = in.nextLine();
        items.get((editItem - 1)).setName(newName);
MTCoster
  • 5,307
  • 3
  • 25
  • 46
Sharkmen
  • 63
  • 4
  • Sorry but the code you posted, is it the version you have an issue with or is it the version that solved your issue? – Joakim Danielson Jan 29 '19 at 11:58
  • 1
    It is not nextLine()'s problem. I guess that you are making some nextInt() calls before the nextLine().nextInt() does not take newline character,so after this,newline is taken by nextLine(). Thus, you should clear newlines after nextInt() or etc. to use nextLine() as you desire. – Y.Kakdas Jan 29 '19 at 12:00
  • @Y.Kaskadas actually you are right, there is in.nextInt before to choose which item you want to edit, thank you – Sharkmen Jan 29 '19 at 17:34

1 Answers1

2

Please visit the below links for better understanding why nextline() does not read input :

Scanner is skipping nextLine() after using next() or nextFoo()?

https://www.quora.com/Why-so-when-I-used-to-take-string-input-through-nextLine-method-of-scanner-class-in-Java-it-does-not-read-my-input

Bishal Dubey
  • 160
  • 6
  • Please provide some explanation to your answer, see the section "Provide context for links" in [this Help article](https://stackoverflow.com/help/how-to-answer). I am amazed this answer has 2 up votes – Joakim Danielson Jan 30 '19 at 08:05