recursivePython recursivePython - 1 year ago 113
Java Question

Reading multiple data types from a CSV file in Java

So I want to create a constructor that reads in a line of a file from a csv and save the first token into a variable and the remaining tokens into an array. This constructor will be used in a gradebook application but being new to txt/file manipulation I'm having a hard time.

A line will look like:

Billy Bob,68,79,95,83

I want to separate the tokens into these:

name = Billy Bob

grades[] = "68,79,95,83"

here is the code I have so far:


public class gradeBook {

public static void main(String[] args){

System.out.println("Java Grade Book version 1.0");

int lineCounter = 0;
String array[];

File data = new File("/file/path/that/works");
InputStream f = new FileInputStream(data);
BufferedReader br = new BufferedReader(new InputStreamReader(f));

for (String line = br.readLine(); line != null; line = br.readLine()) {
System.out.println(line); // just here to check that the code is working thus far

//insert code here
//name should equal first token (which is two names like Billy Bob)
//grades[] should contain the other double type tokens (e.g. 56,87,89,90)

catch(Exception e){
System.err.println("Error: File Couldn't Be Read");

And I want to loop through the file to get as many students as are on the file stored so I can manipulate the grades for averages among other things. This is a personal project to help improve my developing skills so any help, useful tutorial links, and tips will be greatly appreciated. But please don't suggest simplistic examples like the many tutorials I have already read that only use one data type.

Thanks for any help!

Answer Source

Split the line into an array;

String[] input = line.split(",");

String variable = input[0];

int[] grades= new int[input.lenght - 2];

for(int i = 1; i < input.length; i++)
    grades[i] = input[i];// you might have to do Integer.pareseInt(input[i]);

I did not write this in an IDE, but the logic should be correct. You are going to run into a new problem. You grade book will only contain the last entry. Try using a 2D array for grades and 1D array for names; I personally would not use arrays. I would use arraylist.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download