0

I am currently working on code that requires user response to system.out questions. In a previous assignment this worked perfectly fine, showing the question then allowing user input and continuing to the next question. In this assignment though, I am collecting a character input before asking basic user questions. Here is my code: ```

    System.out.print("\nEnter your selection here: \n");
    menuSelection = input.next().charAt(0);
    System.out.println("\nWhat is your name?\n");
    userName = input.nextLine();
    System.out.println("What item will you be purchasing?\n");
    itemName = input.nextLine();
    System.out.println("What is the original price?\n");
    originalPrice = input.nextDouble();
    System.out.println("How many will you purchase?\n");
    howMany = input.nextInt();

    ```

When I run the code the first line outputs correctly and prompts input, but after inputting the character it then displays both the userName and itemName questions at the same time. What could be causing this?

Chris G
  • 7,957
  • 4
  • 17
  • 29
  • JavaScript is a separate language and has nothing to do with Java. Anyway, this is a pretty famous beginner's issue: entering a character then pressing enter means two characters are in the buffer, the enter character is read by the following `nextLine()`, causing it to "skip". To fix this, either don't use `next()` but grab the first character off the entered line, or flush the buffer by inserting a `input.nextLine();`. – Chris G Nov 04 '20 at 09:34
  • 2
    Duplicate: [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – Chris G Nov 04 '20 at 09:35
  • I don't know why is sometimes happens, but `input.nextLine()` doesn't work properly and input an empty value. If you check your inputs probably the userName is equal to null. If it is consider adding `input.nextLine()` before userName input – Andrii Syd Nov 04 '20 at 09:35

0 Answers0