Results 1 to 2 of 2
- 10-09-2011, 04:14 PM #1
Member
- Join Date
- Feb 2009
- Posts
- 18
- Rep Power
- 0
How do I read each character from a file and write it to each index of an array?
Hi all
What I need to do in essence is to read a file that contains the following pattern as shown on the attachment to store each character of the pattern to an index of a multi-dimensional array.
I would like some suggestions on how to go about constructing an nxn array to store the various characters in java.
your suggestions would be greatly appreciated and welcomed.Last edited by coyne20; 10-09-2011 at 04:17 PM.
- 10-09-2011, 06:57 PM #2
Re: How do I read each character from a file and write it to each index of an array?
I've written this code, hope this helps:
There may be a way to jump straight into the 2d char array but I've never tried. I thought this was the best way to solve the problem.Java Code:import java.io.*; import java.util.*; public class SlimeTorpedo { public static void main(String[]args) { File file = new File("SlimeTorpedo.txt"); ArrayList<String> arrayList = new ArrayList<String>(); try { //reads each line from the text file and places it into a string array BufferedReader br = new BufferedReader(new FileReader(file)); String str; while ((str = br.readLine()) != null) { arrayList.add(str); } //creates a stringFormat array and places the strings in the array list onto the stringFormat array String stringFormat[] = new String[arrayList.size()]; arrayList.toArray(stringFormat); //creates 2d char array and writes the characters from the stringFormat array onto the 2d char array char charFormat[][] = new char[stringFormat.length][]; for (int i = 0; i < stringFormat.length; i++) { charFormat[i] = stringFormat[i].toCharArray(); } //for testing purposes, prints the 2d charFormat array for (int i = 0; i < stringFormat.length; i++) { for (int j = 0; j < charFormat[i].length; j++) { System.out.print(charFormat[i][j]); } System.out.println(""); } } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } }
For info on ArrayLists check here: ArrayList (Java Platform SE 6)
For info on 2d char arrays check here: Java: Arrays -- 2-dimensional
Regards Serb.Last edited by SerbianSergeant; 10-09-2011 at 07:01 PM.
Similar Threads
-
how to read array index
By aconti in forum New To JavaReplies: 5Last Post: 08-12-2011, 09:52 PM -
How to read the word character in image file.
By sureshsoftengg in forum Java SoftwareReplies: 1Last Post: 09-21-2010, 03:37 PM -
read the word character in image file
By sureshsoftengg in forum Advanced JavaReplies: 2Last Post: 09-21-2010, 03:36 PM -
How to read and write to a file without taking out the comments in the file
By MAGNUM in forum New To JavaReplies: 5Last Post: 02-05-2009, 10:28 AM -
Read and Write file
By mrdestroy in forum New To JavaReplies: 13Last Post: 10-31-2008, 12:11 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks