零、前言
今天是学习 JAVA语言 打卡的第11天,每天我会提供一篇文章供群成员阅读( 不需要订阅付钱 ),读完文章之后,按解题思路,自己再实现一遍。在小虚竹JAVA社区 中对应的 【打卡贴】打卡,今天的任务就算完成了。
因为大家都在一起学习同一篇文章,所以有什么问题都可以在群里问,群里的小伙伴可以迅速地帮到你,一个人可以走得很快,一群人可以走得很远,有一起学习交流的战友,是多么幸运的事情。
学完后,自己写篇学习报告的博客,可以发布到小虚竹JAVA社区 ,供学弟学妹们参考。
我的学习策略很简单,题海策略+ 费曼学习法。如果能把这100题都认认真真自己实现一遍,那意味着 JAVA语言 已经筑基成功了。后面的进阶学习,可以继续跟着我,一起走向架构师之路。
一、题目描述
题目:有五个学生,每个学生有 3 门课的成绩,从键盘输入以上数据(包括学生号,姓名,三门课成绩),
把这些数据存放在磁盘文件 "stud.txt "中。
二、解题思路
1、写学生键盘输入和成绩键盘输入,Scanner input1 = new Scanner(System.in);
2、把学生和成绩拼接成字符串
3、把字符串保存到硬盘文件 "stud.txt "中。
三、代码详解
public class Basics11 {
public static void fileWriter(String str)
{
FileWriter fw =null;
try {
fw = new FileWriter("D:\\stud.txt", true);
//如["\\stud.txt"]则表示在项目盘符的根目录建立文件,如项目在F盘,则在F盘根目录建立文件
//如["save\\stud.txt"]则表示在当前项目文件夹里找到命名为[save]的文件夹,把文件新建在该文件夹内
System.out.println("数据已成功写入");
fw.write(str);
fw.close();
} catch (Exception e) {
//抛出一个运行时异常(直接停止掉程序)
throw new RuntimeException("运行时异常",e);
}finally {
try {
//操作完要回收流
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
int i,j,k=1;
String id[] = new String[5];
int score[] = new int[15];
String name[] = new String[5];
String str=null;
Scanner inputId = new Scanner(System.in);
Scanner inputName = new Scanner(System.in);
Scanner inputScore = new Scanner(System.in);
for(i=0;i<5;i++)
{
System.out.print("请输入第"+(i+1)+"位同学的学号:");
id[i]=inputId.nextLine();
System.out.print("请输入第"+(i+1)+"位同学的姓名:");
name[i]=inputName.nextLine();
for(j=i*3;j<i*3+3;j++)
{
System.out.print("请输入第"+(i+1)+"位同学的第"+k+++"门成绩:");
score[j]=inputScore.nextInt();
}
k=1;
}
for(i=0;i<5;i++)
{
str="学号"+id[i];
str=str+" "+"姓名"+name[i];
for(j=i*3;j<i*3+3;j++)
str=str+" "+"第"+k+++"门成绩="+score[j];
k=1;
System.out.println();
fileWriter(str+"\r\n");
}
}
}
解法二:引入Hutool
解题思路
1、写学生键盘输入和成绩键盘输入,Scanner input1 = new Scanner(System.in);
2、把学生和成绩拼接成字符串
3、把字符串保存到硬盘文件 "stud.txt "中。
在上一个解法的基础上,优化了第三步,使用
将String写入文件,UTF-8编码追加模式
FileUtil.appendUtf8String(str,“D:\stud2.txt”);
代码详解
public class Basics11_2 {
public static void main(String[] args) {
int i,j,k=1;
String id[] = new String[5];
int score[] = new int[15];
String name[] = new String[5];
String str=null;
Scanner inputId = new Scanner(System.in);
Scanner inputName = new Scanner(System.in);
Scanner inputScore = new Scanner(System.in);
for(i=0;i<5;i++)
{
System.out.print("请输入第"+(i+1)+"位同学的学号:");
id[i]=inputId.nextLine();
System.out.print("请输入第"+(i+1)+"位同学的姓名:");
name[i]=inputName.nextLine();
for(j=i*3;j<i*3+3;j++)
{
System.out.print("请输入第"+(i+1)+"位同学的第"+k+++"门成绩:");
score[j]=inputScore.nextInt();
}
k=1;
}
for(i=0;i<5;i++)
{
str="学号"+id[i];
str=str+" "+"姓名"+name[i];
for(j=i*3;j<i*3+3;j++)
str=str+" "+"第"+k+++"门成绩="+score[j];
str +="\n";
k=1;
try {
//不需要关闭文件流,源码已经有了
FileUtil.appendUtf8String(str,"D:\\stud2.txt");
}catch (IORuntimeException e){
//抛出一个运行时异常(直接停止掉程序)
throw new RuntimeException("运行时异常",e);
}
}
}
}
四、推荐专栏
《JAVA从零到壹》
《JAVA从零到壹》第三讲:条件循环
11hutool实战:FileUtil 文件工具类(写入,追加文件)
五、示例源码下载
关注下面的公众号,回复筑基+题目号
筑基11