Reputation: 11
Okay, so I have this piece of code to take my .csv file which has these values in it.
Alice Jones,80,90,100,95,75,85,90,100,90,92
Bob Manfred,98,89,87,89,9,98,7,89,98,78
I want to take the names and then the corresponding grades and calculate an average for them. The part that I am stuck on is actually retrieving these values in the file so I can actually use them. What would I use to read the string so I can pull the integers out?
import java.io.*;
import java.util.*;
public class Grades {
public static void main(String args[]) throws IOException
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("filescores.csv");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Upvotes: 0
Views: 121
Reputation: 115378
Here is the code snippet that should help you to start.
String[] parts = strLine.split(",");
String name = parts[0];
int[] numbers = new int[parts.length - 1];
for (int i = 0; i < parts.length; i++) {
numbers[i] = Integer.parseInt(parts[i+1]);
}
Upvotes: 1
Reputation: 114797
I'd recommend String#split
to read the values of one line into an array:
String[] values = strLine(",");
// debug
for (String value:values) {
System.out.println(value);
}
The value at index 0 is the name, the other array fields contain the numbers as strings and you could use Integer#parseInt
to convert them into integer values.
Upvotes: 0