You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java编写的GPA计算器中正确实现for循环功能?

你现有代码存在以下几个问题需要修复:

  • for循环语法错误:你写的for ();多了末尾的分号,同时没有设置循环4次的终止条件,会导致循环要么不执行要么只执行一次,无法完成4次输入的要求。
  • switch语句缺少break关键字:case分支执行完后会直接穿透到后续分支,最终只能拿到default分支的计算结果,不符合绩点换算规则。
  • 缺少总绩点、总学分的累加逻辑:你当前的变量只存储了最后一次输入的课程数据,计算GPA时只能拿到最后一门课的结果,无法计算4门课的平均值。
  • GPA计算公式错误:平均GPA需要用总绩点除以总学分,而非单门课的绩点除以单门课学分。

修改后的完整可运行代码如下:

import java.util.Scanner;

public class GpaCalculator {
    public static void main(String[] args) {
        String grade = "";
        int creditHour = 0;
        int totalPoints = 0;
        int totalCredits = 0;
        double gpa = 0.0;
        
        Scanner scnr = new Scanner(System.in);
        
        System.out.println("\t\t\tGPA Calculator");
        System.out.println("This program will calculate GPA based on 4 course grades");
        
        // 循环4次录入课程信息
        for(int i = 0; i < 4; i++) {
            System.out.print("Enter grade: ");
            grade = scnr.nextLine().trim().toUpperCase(); // 兼容小写字母输入
            
            System.out.print("Enter number of credits for grade: ");
            creditHour = Integer.parseInt(scnr.nextLine());
            
            // 计算单门课绩点并累加
            int pointsPerCourse = 0;
            switch (grade) {
                case "A":
                    pointsPerCourse = 4 * creditHour;
                    break;
                case "B":
                    pointsPerCourse = 3 * creditHour;
                    break;
                case "C":
                    pointsPerCourse = 2 * creditHour;
                    break;
                case "D":
                    pointsPerCourse = 1 * creditHour;
                    break;
                default:
                    pointsPerCourse = 0;
            }
            totalPoints += pointsPerCourse;
            totalCredits += creditHour;
        }
                
        // 计算平均GPA
        gpa = (double) totalPoints / totalCredits;
        System.out.printf("The GPA is %.1f ", gpa);

        scnr.close();
    }
}

修改后效果说明:

  1. 循环设置为固定执行4次,满足题目要求的4次输入需求
  2. 每个case后添加break终止分支,避免穿透问题
  3. 新增totalPoints和totalCredits两个变量,每次循环后累加对应值,用于最终平均GPA计算
  4. 新增输入小写兼容处理,用户输入a/b等小写字母也能正常识别
  5. 修正了GPA计算公式,用总绩点除以总学分得到正确的平均结果

内容的提问来源于stack exchange,提问作者ryanmonty42

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 04:06:03