Java新手求排查修正成绩分布柱状图代码错误并生成可运行版本
Java成绩分布柱状图作业修复方案
原代码核心问题清单
- 未实现调用的
print_header()方法,直接调用会抛出编译错误 - 循环计数器错误使用
double类型,应使用整型int - switch分支内仅写了字符串字面量,没有加输出语句,不会产生任何打印效果
- 大量变量(Acent、Bcent、array、array2等)未预先定义就直接使用
- 误用C++的
<<运算符做字符串拼接,Java字符串拼接应使用+ - 代码块括号不匹配,缺少多处闭合括号
- 使用了不存在的
System.out.prdoubleln方法,正确方法为System.out.println - 缺少用户成绩输入的核心逻辑,没有数据源无法生成分布图
修复后可运行完整代码
import java.util.Scanner; public class GradeDistribution { // 实现打印头部的方法 public static void print_header() { System.out.println("******************************************************"); System.out.println("This program will present the number of grades"); System.out.println("you input for grades A-F and turn this information"); System.out.println("in to a bar graph for ease."); System.out.println("******************************************************"); System.out.println(" "); } public static void main(String[] args) { print_header(); Scanner kb = new Scanner(System.in); // 定义变量存储各等级成绩数量 int countA = 0, countB = 0, countC = 0, countD = 0, countF = 0; System.out.print("请输入你要录入的成绩总数量:"); int total = kb.nextInt(); kb.nextLine(); // 消去输入数字后的换行符 // 循环录入成绩 for (int i = 0; i < total; i++) { System.out.print("请输入第" + (i+1) + "个成绩的等级(A/B/C/D/F):"); char grade = kb.nextLine().toUpperCase().charAt(0); switch (grade) { case 'A': countA++; break; case 'B': countB++; break; case 'C': countC++; break; case 'D': countD++; break; case 'F': countF++; break; default: System.out.println("输入的等级无效,已忽略"); i--; // 本次输入无效,重输 } } kb.close(); // 计算各等级占比百分比 double percentA = total == 0 ? 0 : (countA * 100.0 / total); double percentB = total == 0 ? 0 : (countB * 100.0 / total); double percentC = total == 0 ? 0 : (countC * 100.0 / total); double percentD = total == 0 ? 0 : (countD * 100.0 / total); double percentF = total == 0 ? 0 : (countF * 100.0 / total); double[] percents = {percentA, percentB, percentC, percentD, percentF}; char[] grades = {'A', 'B', 'C', 'D', 'F'}; // 输出柱状图 System.out.println("\n成绩分布柱状图:"); System.out.println(" 0 10 20 30 40 50 60 70 80 90 100"); System.out.println(" | | | | | | | | | | |"); System.out.println("******************************************************"); for (int i = 0; i < grades.length; i++) { System.out.print(grades[i] + ": |"); // 每2%打印一个星号 for (int j = 0; j < percents[i] / 2; j++) { System.out.print("*"); } System.out.println(" " + String.format("%.1f", percents[i]) + "%"); } System.out.println("\n录入的总成绩数量:" + total); System.out.printf("A等级:%d个,B等级:%d个,C等级:%d个,D等级:%d个,F等级:%d个", countA, countB, countC, countD, countF); } }
使用说明
- 运行程序后先输入要录入的成绩总数量
- 依次输入每个成绩对应的等级(不区分大小写)
- 所有成绩录入完成后会自动输出百分比柱状图和各等级统计数据
内容的提问来源于stack exchange,提问作者Blankname
相关产品推荐
相关产品推荐

