-1

Below is the java program:-

import java.util.Scanner;
public class Program{
public static void main(String args[]){
    Scanner sc=new Scanner(System.in);
    boolean state=true;
    while(state){
        System.out.println("Welcome");
        System.out.println("Press 1 to enter your name ");
        System.out.println("Press 2 to exit");
        int input =sc.nextInt();
        switch(input){
            case 1:{
                System.out.print("Enter your name : ");
                String name=sc.nextLine();
                //String name=sc.next();
                System.out.println("Your name is\""+name+"\" and it is a beautiful name.");
            }
            break;
            case 2:{
                System.out.println("Goodbye");
                state=false;
            }
            break;
            default:{
                System.out.println("Wrong input");
            }
        }
    }
    sc.close();
}

}

I ran this program and when i entered 1 as input i was unable to enter value of name variable and it printed on its own and then continued the execution but when i used next() in place of nextLine() the program worked properly. Why i am not able to use nextLine() here?

  • Possible duplicate of [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – Ivar Mar 14 '19 at 09:53
  • 3
    Possible duplicate of [What's the difference between next() and nextLine() methods from Scanner class?](https://stackoverflow.com/questions/22458575/whats-the-difference-between-next-and-nextline-methods-from-scanner-class) – Iamat8 Mar 14 '19 at 09:58

1 Answers1

0

next() places the cursor in the same line after reading the input. nextLine() reads input including space between the words

NPE
  • 388
  • 1
  • 13