Java-从文件读取并在特定值处停止
目标是从具有字符串和整数的给定文件中读取。该文件包含虚拟学生的姓名及其考试成绩。有些学生有三个考试分数,有些有四个,有些根本没有。程序应该停止并处理学生的测试分数的方式是当它找到“-1”时。一旦找到“-1”,它应该停止循环,并处理学生的分数。我不明白的是,当程序遇到“-1”时,如何让它停止 当我现在运行它时,它所做的就是捕获所有学生的名字,以及他们的第一次考试分数Java-从文件读取并在特定值处停止,java,Java,目标是从具有字符串和整数的给定文件中读取。该文件包含虚拟学生的姓名及其考试成绩。有些学生有三个考试分数,有些有四个,有些根本没有。程序应该停止并处理学生的测试分数的方式是当它找到“-1”时。一旦找到“-1”,它应该停止循环,并处理学生的分数。我不明白的是,当程序遇到“-1”时,如何让它停止 当我现在运行它时,它所做的就是捕获所有学生的名字,以及他们的第一次考试分数 //Declare Variables String name; String grade; Str
//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(分数==-1){
打破
}
您可以在条件内定义分数。甚至,如果分数超过100怎么办?在条件行中,您可以定义例如
if(score100)
以便在文件数据行中找到-1,您需要解析该行,以查看它是否实际存在于同一行中包含的其他数据值中
在您的情况下,由于数据文件中包含的分数数据行(可能)在需要处理时总是以-1值结尾,因此您可以使用该方法或该方法。由于文本数据文件中的数据始终是字符串类型,因此使用字符串方法轮询数据似乎很自然
是的,如果使用适当的扫描方法,您可以将数据作为数字数据类型读入,但我认为您现在应该保持简单,只将所有内容作为字符串进行检索,因为您将所有内容都作为字符串进行检索,因此使用适当的扫描方法来检查是否有其他文件数据行要读取(对于while循环条件)是方法而不是方法。Scanner#hasNext()方法更倾向于检索字符串标记(单词),而不是整个字符串行。记住以下while循环条件更合适:
while (scanFile.hasNextLine()) {
// .... your loop code ....
}
将该方法与该方法结合使用:
由于您正在从每个文件数据行中查找特定标准,例如学生姓名,学生分数,特别是-1从学生分数的末尾,您可以安全地使用字符串35;endsWith()查看分数数据行中是否包含-1的方法,例如:
while (scanFile.hasNextLine()) {
name = scanFile.nextLine();
scroresString = scanFile.nextLine();
if (scroresString.trim().endsWith("-1")) {
// Do what needs to be done with the data on this line.
}
}
一旦确定分数数据行末尾确实存在-1,则可以删除该-1并使用字符串#split()将剩余分数数据拆分为字符串数组方法。如果一切顺利,该学生的所有分数将包含在一个字符串数组中,您可以从该数组中提取每个数组元素,将其转换为整数或双精度,并进行所需的计算(无论它们是什么)。这样做还可以打开检查分数数据错误的机会,因为分数中可能存在输入错误,例如字母字符与数值混合
以下是此类机制的总体示例(写入文件由您决定):
Scanner KB=新的扫描仪(System.in);
List noScores=new ArrayList();//没有分数的学生
List notReadyForProcessing=new ArrayList();//分数末尾附加了No-1的学生。
List dataError=new ArrayList();//有分数数据错误的学生
字符串名称=”;
字符串scoresString=“”;
//获取输入文件名
文件studentsFile=null;
字符串infle=null;
while(studentsFile==null){
System.out.print(“输入输入文件名(输入q退出):”;
infle=KB.nextLine();
if(填充等信号情况(“q”)){
System.out.println(“再见”);
System.exit(0);//结束应用程序
}
studentsFile=新文件(infle);
//提供的文件名是否存在?
如果(!studentsFile.exists()){
//不!
studentsFile=null;
System.out.println(“无法找到指定的文件(“+infle”)
+“”!请重试。“+System.lineSeparator());
}
}
System.out.println();
//使用“资源试用”自动关闭扫描仪阅读器
尝试(扫描仪扫描文件=新扫描仪(学生文件)){
//跳过文件中的第一行,因为它是标题行。
scanFile.nextLine();
while(scanFile.hasNextLine()){
//以学生的名字读
name=scanFile.nextLine().trim();
//跳过空行。。。
if(name.equals(“”){
继续;
}
/*如果名称末尾包含-1,则为
显然是因为某种原因被标记的。(除非
文件中有输入错误):p*/
if(name.endsWith(“-1”)){
name=name.replace(“-1”,“名称标记:-1(见记录文件)”);
}
//读入学生的分数
scoresString=scanFile.nextLine();
//如果只有a-1,那么当前学生没有分数
if(scoresString.equals(“-1”)){
//将该学生添加到“无分数”列表中
noScores.add(name+“|”+scoresString);
}
//否则,看看分数的末尾是否是-1
else if(scoresString.endsWith(“-1”)){
//是的!
/*计算平均分。。。
这应该在方法或类中完成。
那里
Scanner KB = new Scanner(System.in);
List<String> noScores = new ArrayList<>(); // Students with No Scores Avbailable
List<String> notReadyForProcessing = new ArrayList<>(); // Students with No -1 attached to end of scores.
List<String> dataError = new ArrayList<>(); // Students With Score Data Errors
String name = "";
String scoresString = "";
//Get input file name
File studentsFile = null;
String inFile = null;
while (studentsFile == null) {
System.out.print("Enter the input file name (enter q to quit): ");
inFile = KB.nextLine();
if (inFile.equalsIgnoreCase("q")) {
System.out.println("Bye-Bye");
System.exit(0); // End Application
}
studentsFile = new File(inFile);
// Does the supplied file name exist?
if (!studentsFile.exists() ) {
// Nope!
studentsFile = null;
System.out.println("Can not locate the file specified (" + inFile
+ ")! Please try again." + System.lineSeparator());
}
}
System.out.println();
// Using 'Try With Resouces' so as to auto-close the Scanner reader
try (Scanner scanFile = new Scanner(studentsFile)) {
//Skip first line in file since it's a Header Line.
scanFile.nextLine();
while (scanFile.hasNextLine()) {
// Read in the Student Name
name = scanFile.nextLine().trim();
// Skip blank lines...
if (name.equals("")) {
continue;
}
/* If a name contains a -1 at the end then it is
obviously flagged for some reason. (unless that
was a typo in the file) :p */
if (name.endsWith("-1")) {
name = name.replace("-1", "| Name Flagged: -1 (see records file)");
}
// Read in the Student's Scores
scoresString = scanFile.nextLine();
// If there is just a -1 then the current student has no scores
if (scoresString.equals("-1")) {
// Add the Student to the 'No Scores' List
noScores.add(name + " | " + scoresString);
}
// Otherwise, see if -1 is at end of the scores
else if (scoresString.endsWith("-1")) {
// YUP!
/* Calculate Scores Average...
This should realy be done in a method or Class.
There are MANY WAYS to simplify this code. The hope is that this will
give you ideas for other possible situations in the future.
======================================================================
*/
// Get rid of the -1 at the end of scores String
String procScores = scoresString.substring(0, scoresString.lastIndexOf("-1")).trim();
// Place the Scores into a Integer Array.
// First, Split the scores into a String Array since it all starts as string
String[] strgScoresArray = procScores.split("\\s+");
// Then convert each array element into Integer data type
// and sum them.
double scoreTotal = 0.0d;
double scoreAverage = 0.0d;
int validScoreCount = 0;
for (int i = 0; i < strgScoresArray.length; i++) {
/* Make sure the String numerical value is indeed
a string representation of a Integer or Double
numerical value. */
if (strgScoresArray[i].matches("-?\\d+(\\.\\d+)?")) {
scoreTotal += Double.parseDouble(strgScoresArray[i]);
validScoreCount++;
}
else {
// Falty data...Save the Student record into the dataError List.
dataError.add(name + " | " + scoresString + " | Element In Error: " + strgScoresArray[i]);
}
}
// Calculate the average Score:
scoreAverage = scoreTotal / validScoreCount;
// Display the results to Console Window...
System.out.println("Student Name:\t" + name);
System.out.println("Student Scores:\t" + procScores);
System.out.println("Average Score:\t" + scoreAverage
+ " From '" + validScoreCount + "' Valid Score Results."
+ System.lineSeparator());
}
// Otherwise, Place the current Student into the
// 'Not Ready For Processing' List
else {
notReadyForProcessing.add(name + " | " + scoresString);
}
}
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
System.out.println();
// Display the other Lists generated (if you like).
System.out.println("Students That Contain No Scores:" + System.lineSeparator()
+ "================================");
if (noScores.isEmpty()) {
System.out.println("NONE");
}
else {
for (int i = 0; i < noScores.size(); i++) {
System.out.println(noScores.get(i));
}
}
System.out.println();
System.out.println("Students Not Ready For The Averaging Process:" + System.lineSeparator()
+ "=============================================");
if (notReadyForProcessing.isEmpty()) {
System.out.println("NONE");
}
else {
for (int i = 0; i < notReadyForProcessing.size(); i++) {
System.out.println(notReadyForProcessing.get(i));
}
}
System.out.println();
System.out.println("Students Records With Score Data Errors:" + System.lineSeparator()
+ "========================================");
if (dataError.isEmpty()) {
System.out.println("NONE");
}
else {
for (int i = 0; i < dataError.size(); i++) {
System.out.println(dataError.get(i));
}
}