Reputation: 31
I'm currently working on a java project. I'm making a phone-book. I use switch to select whether the user wants to input the number or a name. The problem is that when I use the switch, which tells the user to input the number it works just fine, but when I use the 'choice' which makes the user input the String it doesn't work. In the run box I can't input the String. Pls help. Here's the code. case 1 and case 3 aren't working.
int choice = scan.nextInt();
switch(choice){
case 1:
System.out.println("\nWho would you like to call?");
name = scan.nextLine();
CallContact(name);
break;
case 2:
System.out.println("\nWhich coontact You Want to Search?");
break;
case 3:
System.out.println("\nWhich Name You Want to Save?");
name = scan.nextLine();
System.out.println("\nWhat is the Number of the person you want to save?");
long number = scan.nextLong();
SaveContact(name, number);
break;
default:
}
}
Upvotes: 2
Views: 73
Reputation: 108
Always use scan.nextLine() to receive the input and then convert received input in your desired format.
int choice = Integer.parseInt(scan.nextLine());
Upvotes: 1
Reputation: 2051
First of all you forgot put break in the default case but it does not effect to solve your usecase. This behavior is happen because when you are taking input with scan.nextInt() its set pointer at the end of that particular line. So just make habit if you are taking input of int then immediate you want to take input of string then just add extra scan.nextLine() before next input.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String name = new String();
int choice = scan.nextInt();
switch (choice) {
case 1:
scan.nextLine();// changes
System.out.println("\nWho would you like to call?");
name = scan.nextLine();
CallContact(name);
break;
case 2:
scan.nextLine();
System.out.println("\nWhich Contact You Want to Search?");
name = scan.nextLine();// changes
break;
case 3:
scan.nextLine();// changes
System.out.println("\nWhich Name You Want to Save?");
name = scan.nextLine();
System.out.println("\nWhat is the Number of the person you want to save?");
long number = scan.nextLong();
SaveContact(name, number);
break;
default:
break;//improve
}
}
Upvotes: 1