编写一个程序:要求从idea控制台以提问对话的形式,输入三个同学的姓名、年龄、c语言成绩与java成绩,并将数据保存到一个“chengji.txt”的文件中. 提示: 创建一个Student学生类,其中域变量包括name,age,javaScore和cScore; 创建一个TestChengji类,在main主方法中创建一个学生对象数组, StudentInfo=new Student[3] 将控制台输入的数据保存在数组中,然后再将数组中的成绩到一个文件中。(写入对象PrintWriter或者使用对象流) 尽量使用带缓冲的数据流
时间: 2023-07-16 11:17:27 浏览: 82
好的,以下是代码实现:
```java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class TestChengji {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Student[] students = new Student[3];
for (int i = 0; i < students.length; i++) {
System.out.println("请输入第" + (i + 1) + "个学生的姓名、年龄、C语言成绩和Java成绩:");
String name = scanner.next();
int age = scanner.nextInt();
double cScore = scanner.nextDouble();
double javaScore = scanner.nextDouble();
students[i] = new Student(name, age, cScore, javaScore);
}
try (PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("chengji.txt")))) {
for (Student student : students) {
writer.println(student.getName() + " " + student.getAge() + " " + student.getcScore() + " " + student.getJavaScore());
}
System.out.println("成绩已保存到chengji.txt文件中。");
} catch (IOException e) {
System.out.println("保存文件出错:" + e.getMessage());
}
}
}
class Student {
private String name;
private int age;
private double cScore;
private double javaScore;
public Student(String name, int age, double cScore, double javaScore) {
this.name = name;
this.age = age;
this.cScore = cScore;
this.javaScore = javaScore;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getcScore() {
return cScore;
}
public double getJavaScore() {
return javaScore;
}
}
```
运行程序后,会提示输入三个学生的信息,输入完毕后会将成绩保存到`chengji.txt`文件中。如果保存文件出错,程序会输出错误信息。
阅读全文