0

I am tasked with implementing K nearest neighbor with java. To do so with 2 csv files. One is training and one is test, they contain the data from a census about how much people earn.

An example of some of the file is (this is exactly how it is in the file) :

meta data: age, workclass, fnlwgt, education, education-num, marital-status, occupation, relationship, race, sex, capital-gain, capital-loss, hours-per-week, native-country, earns

example 1: 25, Private, 226802, 11th, 7, Never-married, Machine-op-inspct, Own-child, Black, Male, 0, 0, 40, United-States, <=50K

example 2: 38, Private, 89814, HS-grad, 9, Married-civ-spouse, Farming-fishing, Husband, White, Male, 0, 0, 50, United-States, <=50K

I just do not understand how to take the key information from these files using scanners and file readers, for example if i wanted just the hours each person worked at the simplist.

If you have a basic outline of how to implement this with knn too would be appericated...

sorry for breaking any rules or not understanding full how to ask questions in advance.

2
  • possible duplicate: see answer1 and answer2 Commented Dec 1, 2017 at 21:21
  • dont parse CSV yourself, use a library to parse it. The duplicate mentions Apache Commons CSV. Another is opencsv. Commented Dec 1, 2017 at 21:57

1 Answer 1

0

You can wrap a FileReader in a BufferedReader, then read line-by-line and tokenize with a split(",") or a Scanner. Maybe something like this?

public void readCsv() throws IOException {
    File file = new File("filename.csv");
    FileReader fileReader = new FileReader(file);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    String line;
    String[] tokenizedLine;

    while ((line = bufferedReader.readLine()) != null) {
        tokenizedLine = parse(line);
        // do stuff with your array
    }
}

private String[] parse(String line) { // use split or Scanner
    return line.split(",");
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.