69943

Reading a file into a multidimensional array

I want to read in a grid of numbers (n*n) from a file and copy them into a multidimensional array, one int at a time. I have the code to read in the file and print it out, but dont know how to take each int. I think i need to splitstring method and a blank delimiter "" in order to take every charcter, but after that im not sure. I would also like to change blank characters to 0, but that can wait!

This is what i have got so far, although it doesnt work.

while (count <81 && (s = br.readLine()) != null) { count++; String[] splitStr = s.split(""); String first = splitStr[number]; System.out.println(s); number++; } fr.close(); }

A sample file is like this(the spaces are needed):

26 84 897 426 4 7 492 4 5 158 6 5 325 169 95 31

Basically i know how to read in the file and print it out, but dont know how to take the data from the reader and put it in a multidimensional array.

I have just tried this, but it says 'cannot covernt from String[] to String'

while (count <81 && (s = br.readLine()) != null) { for (int i = 0; i<9; i++){ for (int j = 0; j<9; j++) grid[i][j] = s.split(""); }

Answer1:

Based on your file this is how I would do it:

Lint<int[]> ret = new ArrayList<int[]>(); Scanner fIn = new Scanner(new File("pathToFile")); while (fIn.hasNextLine()) { // read a line, and turn it into the characters String[] oneLine = fIn.nextLine().split(""); int[] intLine = new int[oneLine.length()]; // we turn the characters into ints for(int i =0; i < intLine.length; i++){ if (oneLine[i].trim().equals("")) intLine[i] = 0; else intLine[i] = Integer.parseInt(oneLine[i].trim()); } // and then add the int[] to our output ret.add(intLine): }

At the end of this code, you will have a list of int[] which can be easily turned into an int[][].

Answer2:

private static int[][] readMatrix(BufferedReader br) throws IOException { List<int[]> rows = new ArrayList<int[]>(); for (String s = br.readLine(); s != null; s = br.readLine()) { String items[] = s.split(" "); int[] row = new int[items.length]; for (int i = 0; i < items.length; ++i) { row[i] = Integer.parseInt(items[i]); } rows.add(row); } return rows.toArray(new int[rows.size()][]); }

Answer3:

<strong>EDIT: You just updated your post to include a sample input file, so the following won't work as-is for your case. However, the principle is the same -- tokenize the line you read based on whatever delimiter you want (spaces in your case) then add each token to the columns of a row.</strong>

You didn't include a sample input file, so I'll make a few basic assumptions.

Assuming that the first line of your input file is "n", and the remainder is the n x n integers you want to read, you need to do something like the following:

public static int[][] parseInput(final String fileName) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(fileName)); int n = Integer.parseInt(reader.readLine()); int[][] result = new int[n][n]; String line; int i = 0; while ((line = reader.readLine()) != null) { String[] tokens = line.split("\\s"); for (int j = 0; j < n; j++) { result[i][j] = Integer.parseInt(tokens[j]); } i++; } return result; }

In this case, an example input file would be:

3 1 2 3 4 5 6 7 8 9

which would result in a 3 x 3 array with:

row 1 = { 1, 2, 3 } row 2 = { 4, 5, 6 } row 3 = { 7, 8, 9 }

If your input file doesn't have "n" as the first line, then you can just wait to initialize your final array until you've counted the tokens on the first line.

Recommend

  • Extract and multiple integers from user-input string in Ruby?
  • RewriteCond and rewriteRule to redirect depending on the domain
  • How to read data from socket connection - android
  • Python: Adding to dict of one object in a list changes all dicts of every other object in the list
  • C# where to add a method
  • Modifying files nested in tar archive
  • Combining many rectangles into fewer rectangles
  • vi mode to emacs mode while on R
  • setSelected() with JRadioButton r[]=new JRadioButton[3] not working [duplicate]
  • Updating and removing unique join relationships in CakePHP
  • If statement skipping right to else after being called once?
  • Validate jQuery plugin, field not required
  • Invalid Date on validation Date of js
  • JqueryMobile Popup menu is not working
  • Object and struct member access and address offset calculation
  • Android application: how to use the camera and grab the image bytes?
  • App restarts from wrong activity
  • Hardware Accelerated Image Scaling in windows using C++
  • preg_replace Double Spaces to tab (\\t) at the beginning of a line
  • Magento Fatal error: Maximum execution error solution, on WAMP
  • How to clear text inside text field when radio button is select
  • Jetty Server not starting: Unable to establish loopback connection
  • Scrapy recursive link crawler
  • Optimizing database types to compact database (SQLite)
  • How to make a tree having multiple type of nodes and each node can have multiple child nodes in java
  • TFS: Get latest causes slow project reloading
  • Running a C# exe file
  • sending/ receiving email in Java
  • How to set my toolbar fixed while scrolling android
  • Timeout for blocking function call, i.e., how to stop waiting for user input after X seconds?
  • AT Commands to Send SMS not working in Windows 8.1
  • Linker errors when using intrinsic function via function pointer
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • Proper folder structure for lots of source files
  • How does Linux kernel interrupt the application?
  • LevelDB C iterator
  • apache spark aggregate function using min value
  • Sorting a 2D array using the second column C++
  • Reading document lines to the user (python)
  • How can i traverse a binary tree from right to left in java?