简体   繁体   中英

How to read only part of a text file in Java?

So I have a text file with grades for assignments.

LABS
100
90
90
90
90
85
80
HOMEWORK
100
100
0
100
100
50

I've written code that successfully reads the file, but now I'm trying to be able to find the averages of both the Lab and the Homework grades. How do I make it so only certain lines are read so I can take only the lab grades or only the homework grades to be averaged? Do I need an array?

import java.util.Scanner;
import java.io.*;
public class FinalGradeCalculator {

//Read from file

public static void main(String[] args) {
    String fileName = "grades.txt";
    Scanner fileScanner = null;//Initialize fileScanner
    System.out.println("The file " + fileName + " contains the following lines:\n");
    try
    {
        fileScanner = new Scanner(new File(fileName));
    }
    catch(Exception e)
    {
        System.out.println(e);
    }
    while(fileScanner.hasNextLine())
    {
        String fileLine = fileScanner.nextLine();
        System.out.println(fileLine);
    }
    fileScanner.close();
}
}

Use an ArrayList and add to it all lines after "LABS" and before "HOMEWORK", then use IntStream#sum to combine the numbers and divide by List#size to get the average:

ArrayList<Integer> labs = new ArrayList<Integer>();
while (fileScanner.hasNextLine()) {
    String fileLine = fileScanner.nextLine();
    if (fileLine.equalsIgnoreCase("labs"))
        continue;
    if (fileLine.equalsIgnoreCase("homework"))
        break;
    labs.add(Integer.parseInt(fileLine));
}
fileScanner.close();
System.out.println("Labs average: " + labs.stream().mapToInt(i -> i).sum()/labs.size());

I personally prefer avoiding hardcoding. As your case is looking for a number and wants to avoid words in general you can do something like this:

ArrayList<Integer> marks = new ArrayList<Integer>();
while (fileScanner.hasNextLine()) {
    String fileLine = fileScanner.nextLine();
    if (isInteger(fileLine)){
            marks.add(Integer.parseInt(fileLine));
        }   
    }
}
fileScanner.close();
System.out.println("Labs average: " + marks.stream().mapToInt(i -> i).sum()/marks.size());

Where isInteger() is as follows:

public static boolean isInteger(String s) {
   boolean isValidInteger = false;
   try
      {
         Integer.parseInt(s);

         // s is a valid integer
         isValidInteger = true;
      }
      catch (NumberFormatException ex)
      {
         // s is not an integer
      }
      return isValidInteger;
   }
}

You can do something similar for Float etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM