Java skipping a line of code? VERY basic java [dup

2019-09-21 16:20发布

This question already has an answer here:

If you look at the line of code where it says

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();

It completely skips the firstname part and goes straight to surname? Any ideas why this is happenimh?

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);
    }
}

标签: java
2条回答
Viruses.
2楼-- · 2019-09-21 17:05

fAge = scanner.nextInt(); does not consume the line ending.

add scanner.nextLine() after that to absorb the end-of-line character and it will work.

查看更多
淡お忘
3楼-- · 2019-09-21 17:10

Add a nextLine() call after you call nextInt(). Because nextInt() doesn't finish the line. So the next call to nextLine() will return an empty string.

查看更多
登录 后发表回答