编写一个程序:要求从DOS控制台以提问对话的形式,输入三个同学的姓名、年龄、c语言成绩与java成绩,并将成绩保存到一个“chengji.txt”的文件中. 提示: 创建一个Student学生类,其中域变量包括name,age,javaScore和cScore; 创建一个TestChengji类,在main主方法中创建一个学生对象数组, Student[] StudentInfo=new Student[3] 将控制台输入的数据保存在数组中,然后再将数组中的成绩到一个文件中。(写入对象PrintWriter或者使用对象流) 尽量使用带缓冲的数据流
时间: 2023-11-22 09:54:32 浏览: 59
下面是您需要的程序:
```java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
public class Student {
private String name;
private int age;
private int cScore;
private int javaScore;
public Student(String name, int age, int cScore, int javaScore) {
this.name = name;
this.age = age;
this.cScore = cScore;
this.javaScore = javaScore;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int getcScore() {
return cScore;
}
public int getJavaScore() {
return javaScore;
}
}
public class TestChengji {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Student[] studentInfo = new Student[3];
for (int i = 0; i < 3; i++) {
System.out.println("请输入第" + (i + 1) + "个学生的姓名、年龄、c语言成绩和java成绩:");
String name = scanner.next();
int age = scanner.nextInt();
int cScore = scanner.nextInt();
int javaScore = scanner.nextInt();
studentInfo[i] = new Student(name, age, cScore, javaScore);
}
try {
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("chengji.txt")));
for (Student student : studentInfo) {
pw.println(student.getName() + " " + student.getAge() + " " + student.getcScore() + " " + student.getJavaScore());
}
pw.close();
System.out.println("成绩已保存到chengji.txt文件中。");
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
运行程序后,在控制台输入三个同学的姓名、年龄、c语言成绩和java成绩,程序会将这些信息保存到chengji.txt文件中。注意,保存的文件路径应该与程序所在的目录相同。
阅读全文