I am currently using a Scanner to record the user input which is a String and print it out. If the user input is a single name such as Alan, it works fine. If I enter a name with spacing such as Alan Smith, it returns an error saying InputMisMatchException.
I read around similar cases here and they advised to use nextLine() instead of next(). It made sense but that doesn't work for me either. When I use a nextLine(), it immediately skips the step where I enter the name and goes back to the starting of the loop asking me to input choice again. Please advice how I can correct this. Thank you.
import java.io.IOException;
import java.util.Scanner;
public class ScannerTest {
static String name;
static Scanner in = new Scanner(System.in);
static int choice;
public static void main(String[] args) {
while(choice != 5){
System.out.print("\nEnter Choice :> ");
choice = in.nextInt();
if(choice == 1){
try{
printName();
}
catch(IOException e){
System.out.println("IO Exception");
}
}
}
}
private static void printName()throws IOException{
System.out.print("\nEnter name :> ");
name = in.next();
//name = in.nextLine();
if (name != null){
System.out.println(name);
}
}
}
No comments:
Post a Comment