gpt4 book ai didi

java - 使用扫描仪时输入未分配给我的变量

转载 作者:行者123 更新时间:2023-12-01 12:00:08 28 4
gpt4 key购买 nike

我试图将用户的中间名分配给变量 middleName。当我单步执行代码时,中间名的输入被分配给姓氏。一切都很顺利,直到 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 + "!");
}

}

最佳答案

如果你想一起使用nextLine()和next(),你必须确保在next()之后单独使用nextLine(),否则下一行将被跳过。

例如:

Scanner s = new Scanner();
String word=s.next();
s.nextLine();
String line=s.nextLine();

关于java - 使用扫描仪时输入未分配给我的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28036396/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com