扫描仪跳过输入,可能的空格?

时间:2016-08-24 08:21:20

标签: java

我刚开始使用Java并想修改语法。每当我输入" F"进入genderage大于或等于20我应该提示输入用户是否结婚,由于某种原因扫描仪正在跳过它。其他一切都很好。

输出我得到:

Whats is your gender (M or F): F
First name: Kim
Last name: Kardashian
Age: 32

Are you married, Kim (Y or N)? 
Then I shall call you Ms. Kardashian.

代码:

import java.util.Scanner;

public class GenderGame 
{

    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);

        int age = 0;
        String Gender = null, fName = null, lName = null, M = null, type = null;

        System.out.print("Whats is your gender (M or F): ");
        Gender = sc.nextLine();
        Gender = Gender.toUpperCase();

        System.out.print("First name: ");
        fName = sc.nextLine();

        System.out.print("Last name: ");
        lName = sc.nextLine();

        System.out.print("Age: ");
        age = sc.nextInt();

        if(Gender.equals("F") && age >= 20)
        {
            System.out.print("\nAre you married, " + fName + " (Y or N)? ");
            M = sc.nextLine();
            M = M.toUpperCase();

            if(M.equals("Y"))
            {
                type = "Mrs. ";
                type = type.concat(lName);
            }
            else
            {
                type = "Ms. ";
                type = type.concat(lName);
            }
        }
        else if(Gender.equals("F") && age < 20)
        {
            type = fName.concat(" " + lName);
        }
        else if(Gender.equals("M") && age >= 20)
        {
            type = "Mr. ";
            type = type.concat(lName);
        }
        else if(Gender.equals("M") && age < 20)
        {
            type = fName.concat(" " + lName);
        }
        else
        {
            System.out.println("There was incorrect input. EXITING PROGRAM");
            System.exit(1);
        }

        System.out.println("\nThen I shall call you " +type+ ".");

    }

}

1 个答案:

答案 0 :(得分:1)

nextInt()的{​​{1}}方法将新行字符排除在外,也就是说,它不会消耗它。这个换行符是由Scanner方法使用的,这就是为什么你没有看到它等待你的输入。

要避免这种情况,请在nextLine()之后致电sc.nextLine(),然后保持其余代码不变。

age = sc.nextInt();