我想从我的 if else 陈述中获得更多

  • 本文关键字:陈述中 else if java
  • 更新时间 :
  • 英文 :


我已经在这个问题上搞砸了太久,想从我的 if else 语句中获得更多。所有代码都有效,直到学生的 GPA 和/或 SAT 分数低,但恰好是一个大班的告别演说家。我知道这是闻所未闻的,但如果它不符合该学生的资格,我的代码对我来说就不正确。

我的第一篇文章。 感谢您的任何建议 布莱恩

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("ntStudent Qualifier");
System.out.println("Enter students GPA: ");
double gpa = in.nextDouble();
System.out.println("Enter students SAT score: ");
double sat = in.nextDouble();
System.out.println("nIf student was valedictorin or salutatorian of a school of 1400 or more, Enter y or n");
String highestHonors = in.next();
in.close();     
if (gpa >= 4.0 && sat >= 1100) 
studentQualified();
if (gpa >= 3.5 && sat >= 1300) 
studentQualified(); 
if (gpa >= 3.0 && sat >= 1500) 
studentQualified();
if (highestHonors == "y")
studentQualified();
else
unQualified();
}
public static void studentQualified() {
System.out.println("Student is qualified");
}
public static void unQualified() {
System.out.println("Student is not qualified");
}

}

您可以使用||来组合测试。不要使用==来比较String- 您可以使用String#equalsIgnoreCase(String)。另外,我强烈建议您始终将{}if-else一起使用。喜欢

if ((gpa >= 4.0 && sat >= 1100) || (gpa >= 3.5 && sat >= 1300) ||
(gpa >= 3.0 && sat >= 1500) || highestHonors.equalsIgnoreCase("y")) {
studentQualified();
} else {
unQualified();
}

您需要使用equals()来比较字符串,而不是====将检查字符串是否字面上相同(即占用内存中的相同空间(,而equals()仅检查字符是否相同。

这样的事情应该有效:

if ("y".equals(highestHonors))

编辑:另外,即使您认为不需要它们,也请使用大括号。它使代码看起来更好,并防止有人想要添加另一个分支时出错。

最新更新