Reputation: 3
I am trying to assign the user's middle name to the variable middleName. When I step through the code The input for middleName is being assigned to lastName. It all goes well until the if statement. Any help?
//New instance of a scanner (keyboard) so users can input information
Scanner keyboard = new Scanner(System.in);
//Create variables
String firstName;
String yesOrNo;
String middleName = null;
String lastName;
//Ask user for first name and store input into variable.
System.out.println("What is your first name?");
firstName = keyboard.nextLine();
//Ask user if they have a middle name and store input into variable.
//If not then move to last name
System.out.println("Do you have a middle name? (Y or N)");
while(true)
{
yesOrNo = keyboard.next();
yesOrNo = yesOrNo.toUpperCase();
if("Y".equals(yesOrNo) || "N".equals(yesOrNo))
{
break;
}
else
{
System.out.println("I need to know whether you have a middle name. \nPlease tell me whether you have a middle name. \nY or N");
}
}
if ("Y".equals(yesOrNo))
{
//Ask user for middle name and store input into variable.
System.out.println("What is your middle name?");
middleName = keyboard.nextLine();
}
else
{
middleName = "";
}
//Ask user for last name and store input into variable.
System.out.println("What is your last name?");
lastName = keyboard.nextLine();
//Output messages using the variables.
System.out.println("Welcome " + firstName + " " + middleName + " " + lastName + "!");
System.out.println("Welcome " + firstName + "!");
System.out.println("Welcome " + lastName + ", " + firstName + "!");
}
}
Upvotes: 0
Views: 76
Reputation: 725
If you want to use nextLine() and next() together, you have to make sure to use nextLine() alone right after your next(), otherwise the next line will be skipped.
ex:
Scanner s = new Scanner();
String word=s.next();
s.nextLine();
String line=s.nextLine();
Upvotes: 1