-2

如果您查看它所说的代码行

System.out.println("Please enter the firstname of your favourite female author");
mFirstName = scanner.nextLine();
System.out.println("Please enter her second name");
mSurname = scanner.nextLine();

它完全跳过了名字部分并直接进入姓氏?任何想法为什么会发生这种情况?

import java.util.*;
    'class university{
        public static void main(String[] args){
            Scanner scanner = new Scanner(System.in);
            Person2 mPerson, fPerson;

        String fFirstName, fSurname, mFirstName, mSurname;
        int fAge, mAge;

        System.out.println("Please enter the firstname of your favourite female author");
        fFirstName = scanner.nextLine();
        System.out.println("Please enter her second name");
        fSurname = scanner.nextLine();
        System.out.println("Please enter her age");
        fAge = scanner.nextInt();
         System.out.println("Please enter the firstname of your favourite female author");
         mFirstName = scanner.nextLine();
        System.out.println("Please enter her second name");
        mSurname = scanner.nextLine();
        System.out.println("Please enter her age");
        mAge = scanner.nextInt();
        System.out.print(fPerson);
    }
}
4

2 回答 2

2

通话后添加nextLine()通话nextInt()。因为nextInt()没有完成线。所以下一次调用nextLine()将返回一个空字符串。

于 2013-10-27T22:40:18.013 回答
1

fAge = scanner.nextInt();不消耗行尾。

之后添加scanner.nextLine()以吸收行尾字符,它将起作用。

于 2013-10-27T22:39:57.133 回答