1

This is some code that I found to help with reading in a 2D Array, but the problem I am having is this will only work when reading a list of number structured like:

73
56
30
75
80
ect..

What I want is to be able to read multiple lines that are structured like this:

1,0,1,1,0,1,0,1,0,1
1,0,0,1,0,0,0,1,0,1
1,1,0,1,0,1,0,1,1,1

I just want to essentially import each line as an array, while structuring them like an array in the text file. Everything I have read says to use scan.usedelimiter(","); but everywhere I try to use it the program throws straight to the catch that replies "Error converting number". If anyone can help I would greatly appreciate it. I also saw some information about using split for the buffered reader, but I don't know which would be better to use/why/how.

    String filename = "res/test.txt"; // Finds the file you want to test.


    try{
        FileReader ConnectionToFile = new FileReader(filename);
        BufferedReader read = new BufferedReader(ConnectionToFile);
        Scanner scan = new Scanner(read);

        int[][] Spaces = new int[10][10];
        int counter = 0;
        try{
            while(scan.hasNext() && counter < 10)
            {
                for(int i = 0; i < 10; i++)
                {
                    counter = counter + 1;
                    for(int m = 0; m < 10; m++)
                    {
                        Spaces[i][m] = scan.nextInt();
                    }
                }
            }
            for(int i = 0; i < 10; i++)
            {
                //Prints out Arrays to the Console, (not needed in final)
                System.out.println("Array" + (i + 1) + " is: " + Spaces[i][0] + ", " + Spaces[i][1] + ", " + Spaces[i][2] + ", " + Spaces[i][3] + ", " + Spaces[i][4] + ", " + Spaces[i][5] + ", " + Spaces[i][6]+ ", " + Spaces[i][7]+ ", " + Spaces[i][8]+ ", " + Spaces[i][9]);
            }
        } 
        catch(InputMismatchException e)
        {
            System.out.println("Error converting number");
        }
        scan.close();
        read.close();
    }
    catch (IOException e)
    {
    System.out.println("IO-Error open/close of file" + filename);
    }
}
3
  • Why don't you read the entire thing into a string. Split the string on ","s and then convert it into a 2D array? Commented Jan 23, 2014 at 5:37
  • In your catch statement instead of just printing out "Error converting number" use e.printStackTrace(). or System.out.println(e). That way you can actually see what the error is. Commented Jan 23, 2014 at 5:43
  • Is your issue resolved??? Commented Jan 23, 2014 at 6:19

5 Answers 5

1

I provide my code here.

public static int[][] readArray(String path) throws IOException {
    //1,0,1,1,0,1,0,1,0,1
    int[][] result = new int[3][10];
    BufferedReader reader = new BufferedReader(new FileReader(path));
    String line = null;
    Scanner scanner = null;
    line = reader.readLine();
    if(line == null) {
        return result;
    }
    String pattern = createPattern(line);
    int lineNumber = 0;
    MatchResult temp = null;
    while(line != null) {
        scanner = new Scanner(line);
        scanner.findInLine(pattern);
        temp = scanner.match();
        int count = temp.groupCount();
        for(int i=1;i<=count;i++) {
            result[lineNumber][i-1] = Integer.parseInt(temp.group(i));
        }
        lineNumber++;
        scanner.close();
        line = reader.readLine();
    }
    return result;
}

public static String createPattern(String line) {
    char[] chars = line.toCharArray();
    StringBuilder pattern = new StringBuilder();;
    for(char c : chars) {
        if(',' == c) {
            pattern.append(',');
        } else {
            pattern.append("(\\d+)");
        }
    }
    return pattern.toString();
}
Sign up to request clarification or add additional context in comments.

Comments

0

The following piece of code snippet might be helpful. The basic idea is to read each line and parse out CSV. Please be advised that CSV parsing is generally hard and mostly requires specialized library (such as CSVReader). However, the issue in hand is relatively straightforward.

try {
   String line = "";
   int rowNumber = 0;
   while(scan.hasNextLine()) {
       line = scan.nextLine();
       String[] elements = line.split(',');
       int elementCount = 0;
       for(String element : elements) {
          int elementValue = Integer.parseInt(element);
          spaces[rowNumber][elementCount] = elementValue;
          elementCount++;
       } 
       rowNumber++;
   }
} // you know what goes afterwards

Comments

0

Since it is a file which is read line by line, read each line using a delimiter ",".

So Here you just create a new scanner object passing each line using delimter ","

Code looks like this, in first for loop

           for(int i = 0; i < 10; i++)
                {
                    Scanner newScan=new Scanner(scan.nextLine()).useDelimiter(",");
                    counter = counter + 1;
                    for(int m = 0; m < 10; m++)
                    {
                        Spaces[i][m] = newScan.nextInt();
                    }
                }

Comments

0

Use the useDelimiter method in Scanner to set the delimiter to "," instead of the default space character. As per the sample input given, if the next row in a 2D array begins in a new line, instead of using a ",", multiple delimiters have to be specified.

Example:

 scan.useDelimiter(",|\\r\\n");

This sets the delimiter to both "," and carriage return + new line characters.

Comments

0

Why use a scanner for a file? You already have a BufferedReader:

FileReader fileReader = new FileReader(filename);
BufferedReader reader = new BufferedReader(fileReader);

Now you can read the file line by line. The tricky bit is you want an array of int

int[][] spaces = new int[10][10];
String line = null;
int row = 0;
while ((line = reader.readLine()) != null)
{
    String[] array = line.split(",");
    for (int i = 0; i < array.length; i++)
    {
        spaces[row][i] = Integer.parseInt(array[i]);
    }
    row++;
}

The other approach is using a Scanner for the individual lines:

while ((line = reader.readLine()) != null)
{
    Scanner s = new Scanner(line).useDelimiter(',');
    int col = 0;
    while (s.hasNextInt())
    {
        spaces[row][col] = s.nextInt();
        col++;
    }
    row++;
}

The other thing worth noting is that you're using an int[10][10]; this requires you to know the length of the file in advance. A List<int[]> would remove this requirement.

1 Comment

Thanks so much for the quick reply. the buffered reader snippet works perfectly and makes more sense. The only other question I would have is, "what is the benefit of using buffered reader vs scanner?"

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.