酷代码 AI
菜单
服务商

Java 实现:3 学生成绩计算,含输入合法性、精度处理与异常处理

```java import java.util.Scanner; class Score { int usualScore; int finalScore; // 计算总成绩的方法 public int calculateTotalScore() { return (int) (usualScore * 0.4 + finalScore * 0.6); } } class Student { String studentId; String name; Score chineseScore; Score mathScore; Score physicsScore; // 计算总分的方法 public int calculateTotalScore() { return chineseScore.calculateTotalScore() + mathScore.calculateTotalScore() + physicsScore.calculateTotalScore(); } // 计算平均分的方法 public double calculateAverageScore() { int totalScore = calculateTotalScore(); return Math.round((double) totalScore / 3 * 100.0) / 100.0; } } public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Student[] students = new Student[3]; for (int i = 0; i < 3; i++) { Student student = new Student(); System.out.print("请输入第 " + (i + 1) + " 个学生的学号: "); student.studentId = scanner.nextLine(); System.out.print("请输入第 " + (i + 1) + " 个学生的姓名: "); student.name = scanner.nextLine(); System.out.println("请输入语文成绩的平时成绩和期末成绩: "); Score chineseScore = new Score(); chineseScore.usualScore = scanner.nextInt(); chineseScore.finalScore = scanner.nextInt(); student.chineseScore = chineseScore; System.out.println("请输入数学成绩的平时成绩和期末成绩: "); Score mathScore = new Score(); mathScore.usualScore = scanner.nextInt(); mathScore.finalScore = scanner.nextInt(); student.mathScore = mathScore; System.out.println("请输入物理成绩的平时成绩和期末成绩: "); Score physicsScore = new Score(); physicsScore.usualScore = scanner.nextInt(); physicsScore.finalScore = scanner.nextInt(); student.physicsScore = physicsScore; students[i] = student; } for (Student student : students) { System.out.println("总分: " + student.calculateTotalScore()); System.out.println("平均分: " + student.calculateAverageScore()); } } } ``` 额外需要注意的逻辑点: 1. 输入数据时要确保数据的合法性,例如成绩不能为负数。 2. 在处理浮点数计算平均分时,要注意精度问题,避免出现误差。 3. 代码中的输入部分可以添加异常处理,以应对用户输入非法数据的情况。 ######[AI写代码神器 | 655点数解答 | 2025-04-18 11:41:55]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]