Java成绩统计程序优化:仅展示有效成绩并消除空白行
解决无效成绩导致输出空白行的问题
你的问题出在输出环节:不管记录是否有效(是否为空),你都会遍历打印所有到stu+1的记录,所以无效的空记录会变成空白行。只需要在输出时过滤掉空记录即可,同时可以优化逻辑避免无效记录占用计数。
修改方案
- 新增有效状态标记,仅当成绩有效时才更新
stu计数,避免无效记录占用数组索引; - 输出循环直接遍历有效计数的记录,无需再处理空记录。
修改后的完整代码
import java.util.Scanner; public class GradeReport { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String[][] student = new String[100][3]; int stu = 0, totalp = 0, totalf = 0; for (int h = 0; h < 100; h++) { System.out.print("Enter Name: "); student[h][0] = sc.nextLine(); System.out.print("Enter Grade: "); student[h][1] = sc.nextLine(); boolean isValid = true; try { int grade = Integer.parseInt(student[h][1]); if (grade > 100 || grade < 50) { student[h][0] = ""; student[h][1] = ""; student[h][2] = ""; System.out.println("Invalid Grade"); isValid = false; } else if (grade >= 75) { student[h][2] = "Passed"; totalp++; } else { student[h][2] = "Failed"; totalf++; } } catch (NumberFormatException e) { student[h][0] = ""; student[h][1] = ""; student[h][2] = ""; System.out.println("Invalid Grade: Not a number"); isValid = false; } System.out.print("Add new record (Y/N)?: "); char choice = sc.nextLine().charAt(0); System.out.println(""); // 仅有效记录计入stu计数 if (isValid) { stu++; } if (choice == 'n' || choice == 'N') { break; } } System.out.println("\nGRADE SUMMARY REPORT"); System.out.println("\nName\tGrades\tRemarks"); // 直接遍历有效记录,无需处理空行 for (int i = 0; i < stu; i++) { for (int h = 0; h < student[i].length; h++) { System.out.print(student[i][h] + "\t"); } System.out.println(); } System.out.println("\nTotal Passed: " + totalp); System.out.println("Total Failed: " + totalf); sc.close(); } }
关键修改说明
- 新增
isValid标记,确保只有有效成绩的记录才会被计入stu计数,输出时直接遍历有效记录即可; - 增加异常处理,避免输入非数字成绩导致程序崩溃;
- 彻底跳过无效记录的输出,自然消除空白行问题。
内容的提问来源于stack exchange,提问作者Mai Sakurajima
相关产品推荐
相关产品推荐

