gpt4 book ai didi

java - 扫描仪跳过输入,可能有空格?

转载 作者:行者123 更新时间:2023-12-01 09:34:32 24 4
gpt4 key购买 nike

我刚刚开始使用 Java,想要修改语法。每当我在gender中输入“F”时和age大于或等于 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+ ".");

}

}

最佳答案

ScannernextInt() 方法将换行符保留下来,也就是说,它不会消耗它。这个换行符由您的 nextLine() 方法使用,这就是为什么您看不到它等待您的输入。

要避免这种情况,请在 age = sc.nextInt(); 之后调用 sc.nextLine(),然后保持其余代码不变。

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

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

关于java - 扫描仪跳过输入,可能有空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39118045/

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