编写一个程序:要求从DOS控制台以提问对话的形式,输入三个同学的姓名、年龄、c语言成绩与java成绩,并将成绩保存到一个“chengji.txt”的文件中. 提示: 创建一个Student学生类,其中域变量包括name,age,javaScore和
时间: 2023-07-16 15:16:53 浏览: 86
设计一个学生类Student(学生学号、姓名、数学、英语、计算机成绩;)
5星 · 资源好评率100%
cScore,并使用FileWriter将学生信息写入到文件中。
以下是Java代码示例:
```java
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Student {
private String name;
private int age;
private double javaScore;
private double cScore;
public Student(String name, int age, double javaScore, double cScore) {
this.name = name;
this.age = age;
this.javaScore = javaScore;
this.cScore = cScore;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getJavaScore() {
return javaScore;
}
public double getCScore() {
return cScore;
}
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
FileWriter writer = new FileWriter("chengji.txt");
for (int i = 0; i < 3; i++) {
System.out.println("请输入第" + (i + 1) + "个同学的姓名:");
String name = scanner.next();
System.out.println("请输入第" + (i + 1) + "个同学的年龄:");
int age = scanner.nextInt();
System.out.println("请输入第" + (i + 1) + "个同学的Java成绩:");
double javaScore = scanner.nextDouble();
System.out.println("请输入第" + (i + 1) + "个同学的C语言成绩:");
double cScore = scanner.nextDouble();
Student student = new Student(name, age, javaScore, cScore);
writer.write(student.getName() + " " + student.getAge() + " " + student.getJavaScore() + " " + student.getCScore() + "\n");
}
writer.close();
scanner.close();
}
}
```
运行程序后,在控制台输入三个同学的姓名、年龄、Java成绩和C语言成绩,然后程序会将这些信息写入到一个名为“chengji.txt”的文件中。每个同学的信息占用一行,各项之间用空格分隔。
阅读全文