Search code examples
javaarraysfile-read

Java how to read a txt file and make each line it's own string array


I have an assignment where I have to read data from a text file and sum up the data in each line. Here is the txt file:

Chen Ruolin     9.2 9.3 9   9.9 9.5 9.5 9.6 9.8    
Emilie Heymans  9.2 9.2 9   9.9 9.5 9.5 9.7 9.6    
Wang Xin        9.2 9.2 9.1 9.9 9.5 9.6 9.4 9.8    
Paola Espinosa  9.2 9.3 9.2 9   9.5 9.3 9.6 9.8    
Tatiana Ortiz   9.2 9.3 9   9.4 9.1 9.5 9.6 9.8    
Melissa Wu      9.2 9.3 9.3 9.7 9.2 9.2 9.6 9.8    
Marie-Eve Marleau   9.2 9.2 9.2 9.9 9.5 9.2 9.3 9.8    
Tonia Couch     9.2 9   9.1 9.5 9.2 9.3 9.4 9.6    
Laura Wilkinson 9.7 9.1 9.3 9.4 9.5 9.4 9.6 9.2

A list of names and diving scores. We're supposed to read the data from the file and put it into arrays (I'm guessing each line would be it's own array), drop the highest and lowest scores of each diver and sum up the remaining scores. So, the output for the first line would look something like this:

Chen Roulin: 56.90

The thing I'm stuck on is how to take a line and create an array (a string array, in this case) where it would separate the words and numbers and put them each into an array index. To make it more clear, the array for the first line would be something like:

String chenRoulin[] = {"Chen", "Roulin", "9.2", "9.3", "9", "9.9", "9.5", "9.5", "9.6", "9.8};

With this, I think I would be able to Double.parseDouble the numerical values in the array and sum them up as I explained earlier. I am aware of 2d arrays and have already tried that approach, but was stuck on the same problem, since all the examples I've found so far were creating int or double arrays. Basically, what would be the best/simplest way to make an array out of each line of the file? Thanks in advance for the help. Here's the code I have so far (it's not much):

import java.util.Scanner;
import java.io.*;

public class DivingData{  
  public static void main(String[] args) throws IOException {
    File myFile = new File("diving_data.txt");
    Scanner inputFile = new Scanner(myFile);

    String line = inputFile.nextLine();
    String[] chenRoulin = new String[10];


  }
}

Just to be clear, I'm only asking for assistance on one part of this assignment and not trying to get someone here to do it all for me.


Solution

  • You can use:

    line.split("\\s+");
    

    then for each array element you check if you can convert to double. the expression "\s+" looks for white space delimiters like tabs or space char.