【发布时间】:2021-03-12 00:41:38
【问题描述】:
这段代码应该:
- 使用扫描仪输入创建一个数组并使用String.split
- 计算 GPA 并根据 GPA 和参加的课程数量确定学生是否有资格参加体育运动。
按原样,代码运行正常,但它没有像预期的那样使用 Scanner 输入 或 String.split。
顶部被注释掉的代码是我一直在使用 String.split 的代码,但是当我这样做时,计算 GPA 的 if 语句不起作用。没有错误信息,GPA 只返回 0.0。
有人可以告诉我问题是什么或指出我正确的方向吗? 谢谢。
import java.util.Scanner;
class Main {
public static void main(String[] args) {
//Initialize array
double GPA = 0;
boolean hasF = false;
/*String str = "a,b";
String[] arr = str.split(",");*/
String [] arr = new String [] {"a", "a", "b", "a", "c"}; //change the grades accordingly
double len = arr.length;
System.out.println("Elements of given array: ");
//Loop through the array by incrementing value of i
for (int i = 0; i < len; i++) {
System.out.println(arr[i] + " ");
}
for (String i : arr) {//goes through each value and adds to GPA accordingly
if (i == "a") {
GPA = GPA + 4.0;
}
else if (i == "b") {
GPA = GPA + 3.0;
}
else if (i == "c") {
GPA = GPA + 2.0;
}
else if (i == "d") {
GPA = GPA + 1.0;
}
else if (i == "f"){
GPA = GPA + 0.0;
hasF = true;
}
else {//invalid input?
System.out.println("invalid input: " + i);
return;
}
}
GPA = GPA/len;//calculate GPA
System.out.println("GPA: " + GPA);
if (len < 4) {//determines elegebility
System.out.println("You are ineligable to participate in activities and sport because you are not taking enough classes.");
}
else if (hasF == true && GPA >= 2.0){
System.out.println("You are ineligable to participate in activities and sports because you have an F. Even though your GPA is greater than 2.0 and you are taking enough classes.");
}
else if (hasF == true && GPA <= 2.0) {
System.out.println("You are ineligable to participate in activities and sports because you have an F and your GPA is less than a 2.0.");
}
else if (hasF == false && GPA <= 2.0){
System.out.println("You are ineligable to participate in activities and sports because your GPA is less than a 2.0.");
}
else if (hasF == true){
System.out.println("You are ineligable to participate in activities and sports because you have an F.");
}
else{
System.out.println("You are Eligable to participate in activities and sports. GOOD JOB!!!");
}
}
}
*我已经交了作业,所以你不会帮我作弊
【问题讨论】:
-
字符串比较在java中不能与
==正常工作,你可以尝试使用i.equals("a")吗?或i.equalsIgnoreCase("a") -
另外,我建议在这种情况下使用
switchcase,这样代码会更简洁。 -
我运行你的代码,它运行良好,GPA 是 3.4