2

I am doing an assignment for class where I have to open a text file and convert that said file into a 2d array so I can later access it depending on what the user requests.

So far, my code is this:

public static void main(String[] args) throws  FileNotFoundException {

    //create a scanner with the file as input
    Scanner in = new Scanner(new File("src/EnglishResults06-12Citywide.csv"));

     //check to see if there's a line available in the file
     while(in.hasNextLine()){

         //get the next line
         String line = in.nextLine();

     }

     //close scanner
     in.close();

     //turns file into multi-dimensional array

     String[][] grades = new String[98][15];               

     for (int i=0; i<results.length; i++) { //loop through each row
        for (int j=0; j<results[i].length; j++) { //loop through all columns within the current row

            results[i][j] = request //not sure how to assign the imported csv to the variable request
        }
     }

     System.out.printf("Grade", "Year" , "Demographic" , "Number Tested" , "Mean Scale Score" , "Num Level 1" , "Pct Level 1" , "Num Level 2" , "Pct Level 2" , "Num Level 3" , "Pct Level 3" , "Num Level 4" , "Pct Level 4" , "Num Level 3 and 4" , "Pct Level 3 and 4");

I've imported the following:

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

My text file has 98 rows and 15 columns. Here is the file: http://txt.do/xjar

I hope someone can help. Thank you so much in advanced!!!

5
  • 1
    String.split is your friend, use it. The file format you are referring to is called CSV (comma-separated values), consider adding it as a tag. Commented Mar 25, 2015 at 10:11
  • Thank you for the response!! Where would I exactly use String.split? Commented Mar 25, 2015 at 10:22
  • 1
    @MichaelLaffargue Attention here, the argument of split is a RegEx pattern, so splitting by . will split by any character, if you are unsure, you can escape the argument with Pattern.quote(...) Commented Mar 25, 2015 at 10:32
  • On the line, using split with a Regular Expression you'll receive back an array => Exemple : "my line to split".split("\\s") --> ["my","line","to","split"]. docs.oracle.com/javase/tutorial/essential/regex/… Commented Mar 25, 2015 at 10:36
  • You're comment isn't wrong, I just thought I should mention that this can fail when splitting by special characters... Commented Mar 25, 2015 at 10:36

3 Answers 3

1

If you are not specific about converting it to an array, you could try "csv_ml" http://siara.cc/csv_ml/csvdoc.pdf. GitHub page: https://github.com/siara-cc/csv_ml

The code would be something like this:

import java.io.FileReader;
import java.io.Reader;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import cc.siara.csv_ml.MultiLevelCSVParser;

public class Convert {
   public static void main(String args[]) throws Exception {
     Reader r = new FileReader("input.csv");
     MultiLevelCSVParser parser = new MultiLevelCSVParser();
     JSONObject jso = (JSONObject) parser.parse("jso", r, false);
     String ex_str = parser.ex.get_all_exceptions();
     if (ex_str.equals("")) {
        JSONArray rows = (JSONArray)jso.get("n1");
        System.out.println(((JSONObject)rows.get(0)).get("c1"));
     } else
         System.out.println(ex_str);
   }
}

If you need to refer using your header, you would need to add the following line at the beginning of your CSV file.

csv_ml,1.0,UTF-8,root,no_node_name,inline

Then the column can be referred as:

System.out.println(((JSONObject)rows.get(0)).get("Grade"));

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

0

As you know the number of columns and rows, you can explicitly define the lengths of the 2D array such as:

String[][] myArr = new String[98][];

Because you know the number of columns, you can create a counter outside of the while loop and you can increment it into the while loop. You can then split the line at each comma, and assign it to the 2D array:

int i = 0;
//remember to skip the headers
in.nextLine();
    while(in.hasNextLine()){
         //get the next line
         String line = in.nextLine();
         myArr[i] = line.split(",");
         i++;
     }

You can then print the 2D array:

System.out.println(Arrays.deepToString(myArr));

or you can ask for any column in the ith index such as:

System.out.println(myArr[0][0]);

Hope this helps.

1 Comment

For an excercise, this explicit notation is o.k. - in this case I suggest using a for-loop instead a useless while-loop which counts the line.
0

You can do something like this to split each line by a comma and adding the parts to a list:

public static void main(String[] args) throws IOException {
    //URL source = Program.class.getResource("EnglishResults06-12Citywide.csv"); //embedded resource
    URL source = new File("src/EnglishResults06-12Citywide.csv").toPath().toUri().toURL(); //local file
    Scanner in = new Scanner(source.openStream());
    if (!in.hasNextLine()) { //oops, the file is empty
        System.err.println("Missing headline!");
        System.exit(1);
    }
    String headLine = in.nextLine();
    String[] fieldNames = headLine.split(","); //the headline is like a regular line, it holds the names of the fields
    List<String[]> data = new ArrayList<>(); //backing list (=growable array) for the elements 
    while (in.hasNextLine()) {
        String line = in.nextLine();
        String[] frags = line.split(","); //split line by comma, because it's CSV
        data.add(frags);
    }
    in.close(); //close the stream

    String[][] dataArray = data.toArray(new String[data.size()][]); //copy data from the list to an array

    //print out results
    System.out.println("Field names: " + Arrays.toString(fieldNames));
    System.out.println("Data array: " + Arrays.deepToString(dataArray));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.