使用 Scanner 时未将输入分配给我的变量

Input is not being assigned to my variable while using Scanner

我正在尝试将用户的中间名分配给变量 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();