java - Java - 从文件中读取并在特定值处停止
问题描述
目标是从具有字符串和整数的给定文件中读取。该文件包含虚构学生的姓名及其考试成绩。有些学生有三个考试成绩,有些是四个,有些根本没有。该程序应该停止和处理学生的考试成绩的方式是当它找到“-1”时。一旦找到“-1”,它就应该停止循环,并处理该学生的分数。我想不通的是如何让程序在运行到“-1”时停止。
当我现在运行它时,它所做的只是捕捉所有学生的姓名,以及他们的第一次考试成绩。
//Declare Variables
String name;
String grade;
String inFile;
String outFile;
PrintWriter outputFile;
int score1 = 0;
int score2 = 0;
int score3 = 0;
int score4 = 0;
int score5 = 0;
int score6 = 0;
//Get input file name
System.out.print("Enter the input filename: ");
inFile = KB.nextLine();
File studentsFile = new File(inFile);
Scanner scanFile = new Scanner(studentsFile);
//Capture Student Info
while(scanFile.hasNext()){
name = scanFile.nextLine();
if (scanFile.hasNextInt()){
score1 = scanFile.nextInt();
System.out.println(name);
System.out.println(score1);
}
示例输入文件:
Introduction to Programming 1
John Sweet
87 76 90 100 -1
Ali Hassan
-1
Willy Nilly
73 63 74 70 -1
Juju Smith Jr.
89 90 78 88 -1
Karl Kavington III
90 100 80 70 -1
Lary Howard Holiday
80 77 67 67 -1
Leo Gordon
56 88 780 77 -1
Jessy Brown -1
90 80 88 92 -1
Mr. Perfect
100 100 100 100 -1
Mr. Missing It All
0 0 0 0 0 0 -1
编辑:该程序应该读取一个学生及其考试成绩,执行一些计算,将其写入输出文件,然后与下一个学生重复。它会不断重复,直到文件结束。
解决方案
好吧,如果您想停止读取文件,可以在while
循环内尝试:
if(score == -1 ){
break;
}
您可以在条件内定义分数。甚至,¿如果分数超过 100 怎么办?在条件中,您可以定义例如if(score<0 || score>100)
。
推荐阅读
- c++ - 为什么模板模板参数中的概念没有得到验证?
- php - 如果满足条件,则追加 array_merge
- r - R 中的 memory.limit 和 RAM 使用情况
- javascript - Discord.js:message.guild.channels.cache.filter
- ios - UITableViewCell 阴影叠加
- java - 如何最大限度地减少方向 api 的请求?
- vue.js - 有没有办法从 Vue 3 中的作用域样式定位组件的根元素?
- c# - 使用依赖注入时在 ASP.NET MVC 中注册 FacebookAuthentication
- flutter - Flutter fl_chart:如何为工具提示和其中的值设置动画?用折线图?
- java - OpenApi 授权所有服务