简体   繁体   中英

How to create an array of objects that have strings from a CSV file of strings?

I have some code that reads from a csv file that is full of the last name, first name, and birth year of a lot of people. It looks like this in the csv file:

nameLast    nameFirst   birthYear
Santos      Valerio       1972
Tekulve      Kent         1947
Valentine    Fred         1935

I have a class called Human, and the human class also has these three values. I would like to create an array of the human class, and pass into it all of my data from the csv file. That way, if the first instance of the array at [0] will have three values in it, two for the names and one for the year. Here is the code I have so far:

package testing.csv.files;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Human {

    String lastName;
    String firstName;
    String birthYear;

    public static void main(String[] args) {
        //.csv comma separated values
        String fileName = "C:/Users/Owner/Desktop/Data.csv";
        File file = new File(fileName); // TODO: read about File Names
        try {
            Scanner inputStream = new Scanner(file);
            inputStream.next(); //Ignore first line of titles
            while (inputStream.hasNext()){
                String data = inputStream.next(); // gets a whole line
                String[] values = data.split(",");
                System.out.println(values[2]);
            }
            inputStream.close();

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

What I have here will currently print out all of the birth years, since values[2] is the birth year. I thought that I could change the line

   String[] values = data.split(",");

To read

   Human[] values = data.split(",");

And then it would automatically assign the values lastName, firstName, and birthyear into the right places for every object in the array. However, doing this just produces the error message

   incompatible types: String[] cannot be converted to Human[]

I tried also changing the line above this one from

  String data = inputStream.next(); // gets a whole line

to

  Human data = inputStream.next(); // gets a whole line

but I get the same error message.

So what am I doing wrong? Perhaps I didn't properly define the class as I thought I did, or is there something much more wrong with my approach? Please let me know what you think.

The method split in class String returns an array of Strings, not an array of Human . To create an array of Human , you'll need to parse that String array returned from split into the values human needs.

class Human{
    String firstName;
    String lastName;
    int birthYear;
    public Human(String first, String last, int birthYear){
        this.firstName = first;
        this.lastName = last;
        this.birthYear = birthYear;
    }
}
int numHumansInCSV = //How many humans are in your file?
Human[] humanArray = new Human[numHumansInCSV];
int index = 0;
while (inputStream.hasNext()){
    String data = inputStream.next(); // gets a whole line
    String[] values = data.split(",");
    String lastName = values[0];
    String firstName = values[1];
    int birthYear = Integer.parseInt(values[2]);
    Human human = new Human(firstName, lastName, birthYear);
    //put human in human array.
    humanArray[index] = human;
    index += 1;
}

If you can use a datastructure like List , that'd be more appropriate than an array as you might not know how many humans your CSV file contains.

Also, this parsing code should really be in its own class. If I were writing this, here's what I'd do.

public class HumanCSVReader{

    public List<Human> read(String csvFile, boolean expectHeader) throws IOException{
        File file = new File(csvFile);
        Scanner scanner = new Scanner(file);
        int lineNumber = 0;
        List<Human> humans = new List<Human>();
        while(scanner.hasNextLine()){
            if(expectHeader && lineNumber==0){
                ++lineNumber;
                continue;
            }

            String line = scanner.nextLine();
            String csv = line.split(",");
            if(csv.length!=3)
                throw new IOException("Bad input in "+csvFile+", line "+lineNumber);
            String firstName = list[0];
            String lastName = list[1];
            try{
                int birthYear = Integer.parseInt(list[2]);
            }catch(NumberFormatException e){
                throw new IOException("Bad birth year in "+csvFile+", line "+lineNumber);
            }
            Human human = new Human(fistName, lastName, birthYear);
            humans.add(human);
            ++lineNumber;
        }
        return humans;
    }
}

Just use this to load in your array of humans instead. It'll even handle some basic validation.

First of all, your Human class needs a constructor. Insert the following method.

public Human(String[] str) {
  lastName = str[0];
  firstName = str[1];
  birthYear = str[2];
}

Now, instead of a string array, you can get a Human object using

Human someHuman = new Human(data.split(","));

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