0

This is a simple test I made for my user input of my program but it skips over the second user input part. I am using sc.nextLine()

public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);
    int option;
    String name;

    System.out.println("1 or 2");
    option = sc.nextInt();

    if(option == 1)
    {
        System.out.println("Please enter a name");
        name = sc.nextLine();
        System.out.println(name);
    }
}
NightPixel
  • 27
  • 6
  • The program prints "1 or 2" The user selects 1 then the program prints the "please enter a name" theres a gap and the program ends?????? – NightPixel Oct 22 '19 at 08:56
  • it's a classic issue. After your nextInt(); call, add another sc.next(); – Stultuske Oct 22 '19 at 08:57
  • What do you mean wont that just ask for user input again? – NightPixel Oct 22 '19 at 08:58
  • Similar to [this](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – PftM Oct 22 '19 at 08:58
  • I get what you are saying because thats to do with clearing the buffer? But if I put sc.next(); straight after the sc.nextInt(); it asks for user input again? – NightPixel Oct 22 '19 at 09:01
  • @NightPixel it will treat the enter. – Stultuske Oct 22 '19 at 09:02
  • @Stultuske `next()` __doesn't__ treat the enter/return. You're confusing it with `nextLine()` (or it was a typo in your first comment). – Tom Oct 22 '19 at 09:27
  • 1
    @Tom you're right. Haven't used scanner for over a decade, I recognized the behavior, but ... :) – Stultuske Oct 22 '19 at 09:36

2 Answers2

0

The problem is that the enter ("\n") from the first user input isn't a number and is used for the second. The quick and dirty option to fix this is to add a "sc.nextLine ();" after "nextInt()" line. Like:

    public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);
    int option;
    String name;

    System.out.println("1 or 2");
    option = sc.nextInt();
    sc.nextLine();

    if(option == 1)
    {
        System.out.println("Please enter a name");
        name = sc.nextLine();
        System.out.println(name);
    }
}
-1

Use sc.nextLine() after sc.nextInt() in your code.

Jennis Vaishnav
  • 330
  • 6
  • 29