我一直在做这些基本的java项目,而且我坚持这个: https://programmingbydoing.com/a/gender-game.html 代码的重点是将Mr,Mrs,Ms放在用户名前面。 无论我如何扭曲代码我都无法得到它给我一个年龄> 20和性别M的结果。
String gender,firstname,lastname, married;
String prefix ;
int age;
System.out.println("What is your gender (m or f): ");
gender=kb.next();
System.out.println("First name: ");
firstname=kb.next();
System.out.println("Last name: ");
lastname=kb.next();
System.out.println("Age: ");
age=kb.nextInt();
if(age<20)
System.out.println("Then I shall call you " +firstname+" "+lastname);
if(age>=20 && gender.equals("f"))
System.out.println("Are you married, "+firstname+"(y or n)?");
married=kb.next();
{if (married.equals("y"))
prefix="Mrs. ";
else
prefix="Ms. ";}
if (gender.equals("m"))
prefix="Mr. ";
System.out.println("Then I shall call you "+prefix+" "+lastname+".");
kb.close();
}
}
答案 0 :(得分:0)
你的花括号在你的第二个错误的地方。它应该看起来像:
else if(age>=20)
{
if(gender.equals("f"))
{
System.out.println("Are you married, "+firstname+"(y or n)?");
married=kb.next();
if (married.equals("y"))
prefix="Mrs. ";
else
prefix="Ms. ";
}
else if (gender.equals("m"))
{
prefix="Mr. ";
}
System.out.println("Then I shall call you "+prefix+" "+lastname+".");
}
如果必须在if语句中执行多行代码,则必须将代码放在花括号中。否则,您只需运行第一行。
答案 1 :(得分:0)
你应该这样做。检查年龄,然后检查性别
if(age>=20) {// I would recommend just making this an else, since you already did < 20, so testing age here a second time is a waste
if (gender.equals("f")){
System.out.println("Are you married, "+firstname+"(y or n)?");
married=kb.next();
if (married.equals("y"))
prefix="Mrs. ";
else
prefix="Ms. ";
}
else{
prefix="Mr. ";
}
System.out.println("Then I shall call you "+prefix+" "+lastname+".");
}
kb.close();