我正在尝试将用户的中间名分配给变量middleName。当我单步执行代码时,middleName的输入被分配给lastName。在if语句之前一切顺利。有什么帮助吗?
//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 + "!");
}
}
答案 0 :(得分:1)
如果你想同时使用nextLine()和next(),你必须确保在next()之后单独使用nextLine(),否则将跳过下一行。
例如:
Scanner s = new Scanner();
String word=s.next();
s.nextLine();
String line=s.nextLine();