Java从键盘循环输入学生的姓名和成绩,当学号为0时(或自行设计循环出口),结束输入,计算学生成绩的总分和平均分。
时间: 2024-09-18 20:00:44 浏览: 45
在Java中,你可以使用while循环结合Scanner类获取用户输入来实现这个功能。首先,创建一个Student类来存储学生的信息,如姓名和成绩。然后,在主程序中进行如下操作:
```java
import java.util.Scanner;
class Student {
String name;
double score;
public Student(String name, double score) {
this.name = name;
this.score = score;
}
// 如果需要,可以添加getters和setters方法
@Override
public String toString() {
return "Name: " + name + ", Score: " + score;
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double totalScore = 0.0;
int studentCount = 0;
System.out.println("请输入学生的姓名和成绩(学号为0表示结束输入):");
while (true) {
System.out.print("请输入学号(0结束): ");
int id = scanner.nextInt();
if (id == 0) {
break; // 学号为0时,跳出循环
}
System.out.print("请输入姓名: ");
String name = scanner.next();
System.out.print("请输入成绩: ");
double currentScore = scanner.nextDouble();
Student student = new Student(name, currentScore);
totalScore += currentScore;
studentCount++;
}
scanner.close(); // 关闭扫描器
double averageScore = totalScore / studentCount;
System.out.println("\n学生总数: " + studentCount);
System.out.printf("总分: %.2f\n", totalScore);
System.out.printf("平均分: %.2f\n", averageScore);
}
}
```
阅读全文