java编写一个程序从idea控制台以提问对话的形式输入三个同学的姓名年龄、成绩并将数据保存到一个文件中
时间: 2023-11-22 17:53:33 浏览: 80
好的,下面是一个简单的实现方式:
```java
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] names = new String[3];
int[] ages = new int[3];
double[] scores = new double[3];
for (int i = 0; i < 3; i++) {
System.out.println("请输入第" + (i + 1) + "个同学的姓名:");
names[i] = scanner.next();
System.out.println("请输入第" + (i + 1) + "个同学的年龄:");
ages[i] = scanner.nextInt();
System.out.println("请输入第" + (i + 1) + "个同学的成绩:");
scores[i] = scanner.nextDouble();
}
try {
FileWriter writer = new FileWriter("students.txt");
for (int i = 0; i < 3; i++) {
writer.write(names[i] + "," + ages[i] + "," + scores[i] + "\n");
}
writer.close();
System.out.println("数据已成功保存到文件中");
} catch (IOException e) {
System.out.println("文件保存失败:" + e.getMessage());
}
}
}
```
运行后,控制台会提示用户依次输入三个同学的姓名、年龄、成绩,然后将这些数据保存到文件`students.txt`中。每行数据的格式为`姓名,年龄,成绩`,不同的数据之间用逗号隔开。最后程序会在控制台输出保存成功的消息,或者保存失败的错误信息。
阅读全文