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?