Reading characters from a text file into a multidimensional array?

I have an array, maze[][] that is to be filled with characters from a text file. I've got most of the program worked out (i think) but can't test it because I am reading my file incorrectly. However, I'm running into major headaches with this part of the program.
The text file looks like this: (It is meant to be a maze, 19 is the size of the maze(assumed to be square). is free space, # is block, s is start, x is finish)
This didn't paste evenly, but thats not a big deal. Just giving an idea.
19
5..................
And my constructor looks like follows, I've tried zillions of things with the input.hasNext() and hasNextLine() to no avail.
Code:
//Scanner to read file
Scanner input = null;
try{
input = new Scanner(fileName);
}catch(RuntimeException e) {
System.err.println("Couldn't find the file");
System.exit(0);
//Set the size of the maze
while(input.hasNextInt())
size = input.nextInt();
//Set Limits on coordinates
Coordinates.setLimits(size);
//Set the maze[][] array equal to this size
maze = new char[size][size];
//Fill the Array with maze values
for(int i = 0; i < maze.length; i++)
for(int x = 0; x < maze.length; x++)
if(input.hasNextLine())
String insert = input.nextLine();
maze[i][x] = insert.charAt(x);
Any advice would be loved =D

Code-tags sometimes cause wonders, I replaced # with *, as the code tags interprets # as comment, which looks odd:
******...*.........To your code: Did you test it step by step, to find out about what is read? You could either use a debugger (e.g., if you have an IDE) or system outs to get a clue. First thing to check would be, if the maze size is read correctly. Further, the following loops look odd:for(int i = 0; i < maze.length; i++) {
    for(int x = 0; x < maze.length; x++) {
        if (input.hasNextLine()) {
            String insert = input.nextLine();
            maze[x] = insert.charAt(x);
}Shouldn't the nextLine test and assignment be in the outer loop? And assignment be to each maze's inner array? Like so:for(int i = 0; i < maze.length; i++) {
    if (input.hasNextLine()) {
        String insert = input.nextLine();
        for(int x = 0; x < insert.size(); x++) {
            maze[i][x] = insert.charAt(x);
}Otherwise, only one character per line is read and storing a character actually should fail.

Similar Messages

  • Read words from a text file into an undefined array

    Dear all,
    Does anyone know how to read words in text file, seperated by all types of spaces ("_", "\n", "\t","\r","\f") and put them into a string array to be used later?
    So far I can read the words using the Tokenizer but can't assign to array:
    public class reader
    StringTokenizer tokenizer = new StringTokenizer(input);
    String[ ] array= null;  //unknown size of array
    int i=0;
                   while(tokenizer.hasMoreTokens())
                             array[i] = tokenizer.nextToken();
                             i++;
    Any suggestions welcome!
    thanks in advance!

    Hi
    sorry wrote in a hurry ;) din c the problem clearly
    there are two approaches
    1) best approach for your problem is Vector or ArrayList, these would make life easy for you.
    Always collections are better approach over arrays when the size is dynamic. However in your case the size cant be said to be DYNAMIC. coz the number of words will not grow / shrink during the runtime.. i know that number of words are not fixed but dynamic is something which will grow/shrink during runtime. but still collection is better approach.
    2)dirty approach
    use double dimensional array
    String arr[][] = null;
    then use one tokenizer for StringTokenizer(str,"\n");
    using countTokens on this will give you number of lines.
    use this to initialize array
    arr = new String[lineCount][];
    then iterate from 1 to lineCount and use 1 more tokenizer to get number of words for that line. use this number to initialize the column size for arr[i] like
    arr[i] = new String[wordCount];
    then store the token using nested for loops in this array
    go for the 1st one ;) 2nd one is hedious n time consuming but both will work ;)
    cheers
    amey

  • Reading from a text file into a 2D array

    How do you read from a text file and put it into a 2D array? Or if someone could guide me to where I can find the information?

    This tutorial shows how to read a file:
    http://java.sun.com/docs/books/tutorial/essential/io/scanfor.html
    This tutorial shows how to create arrays with multiple dimensions:
    http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html

  • How do you read data from a text file into a JTextArea?

    I'm working on a blogging program and I need to add data from a text file named messages.txt into a JTextArea named messages. How do I go about doing this?

    Student_Coder wrote:
    1) Read the file messages.txt into a String
    2) Initialize messages with the String as the textSwing text components are designed to use Unix-style linefeeds (\n) as line separators. If the text file happens to use a different style, like DOS's carriage-return+linefeed (\r\n), it needs to be converted. The read() method does that, and it saves the info about the line separator style in the Document so the write() method can re-convert it.
    lethalwire wrote:
    They have 2 different ways of importing documents in this link:
    http://java.sun.com/docs/books/tutorial/uiswing/components/editorpane.html
    Neither of those methods applies to JTextAreas.

  • Reading data from a text file into PAS - Dimension member names truncated

    Hi,
    I created a procedure to dump variables and data into a text file to load into another model. I used a semicolon as a field seperator.
    The data, measures and dimension members are dumped properly into a text file and no dimension member names are truncated .
    However when I read the data into  a measure, and I issue a peek command, dimension meber names are read in truncated
    and remain full names in the text file. Any reason for this? What do I need to do to prevent this from happening?
    THanks.
    Lungile

    Hi Lungile,
    The problem that you're likely having is that you haven't created a file description for the file from which you're reading.  When loading data into Application Server from a text file, you would normally go through three steps:
    1. Enter the ACCESS EXTERNAL subsystem
    2. Specify the name of the file to be read
    3. Specify the format of the file field names, types, widths, and positions.
    If you go into the Application Server help, select "Application Server Help", then "Application Server at the command level", then "Variables and reading in data", and then "Reading an external file", you will have the process of the steps you need to follow outlined for you, including links to the help topic for each command you need to issue.
    So what I think you need to do is use the DESCRIPTION command to specify the names of your fields, their type, and also their width, in order to ensure no truncation of data on the load.
    The same DESCRIPTION statement is required if you want to use your text file as the source of a dimension.
    Hope this helps,
    Robert

  • How to read characters from a text file in java program ?

    Sir,
    I have to read the characters m to z listed in a text file .
    I must compare the character read from the file.
    And if any of the characters between m to z is matched i have to replace it with a hexadecimal value.
    Any help or suggesstions in this regard would be very useful.
    Thanking you,
    khurram

    Hai,
    The requirement is like this
    There is an input file, the contents of the file are as follows, you can assume any name for the file.
    #Character mappings for Japanese Shift-JIS character set
    #ASCII character Mapped Shift-JIS character
    m 227,128,133 #Half width katakana letter small m
    n 227,128,134 #Half width katakana letter small n
    o 227,129,129
    p 227,129,130
    q 227,129,131
    r 227,129,132
    s 227,129,133
    t 227,129,134
    u 227,129,135
    v 227,129,136
    w 227,129,137
    x 227,129,138
    y 227,129,139
    z 227,129,142
    The contents of the above file are to be read as input.
    On encountering any character between m to z, i have to do a replacement with a hexadecimal code point value for the multibyte representation in the second column in the input file.
    I have the code to get the unicode codepoint value from the multibyte representation, but not from a file.
    So if you could please tell me how to get the characters in the second column, it would be very useful for me.
    The character # is used to represent the beginning of a comment in the input file.
    And comment lines are to be ignored while reading the file.
    Say i have a string str="message";
    then i should replace the m with the unicode code point value.
    Thanking you,
    khurram

  • Reading variables from a text file into a flash projector exe

    I am using Flash CS4 and my script is in ActionScript2.
    I am developing a flash projector file that runs when a user puts in a cd to guide them through the steps they need to install a program and then kicks off the installer.
    I use fscommand to run a utility that reads the users registry to determine the PCs regional settings and then writes this to a text file in the users %temp% directory.
    I then use the LoadVariablesNum command to read in the text file and get the variables.
    This was working fine when I had the text file stored in a different directory, but when I try and refer to the %temp% directory, I get an Error opening file message.
    Is there anyway to get flash to look in the %Temp% directory?
    Thanks in advance,
    Carol Lutz

    Code-tags sometimes cause wonders, I replaced # with *, as the code tags interprets # as comment, which looks odd:
    ******...*.........To your code: Did you test it step by step, to find out about what is read? You could either use a debugger (e.g., if you have an IDE) or system outs to get a clue. First thing to check would be, if the maze size is read correctly. Further, the following loops look odd:for(int i = 0; i < maze.length; i++) {
        for(int x = 0; x < maze.length; x++) {
            if (input.hasNextLine()) {
                String insert = input.nextLine();
                maze[x] = insert.charAt(x);
    }Shouldn't the nextLine test and assignment be in the outer loop? And assignment be to each maze's inner array? Like so:for(int i = 0; i < maze.length; i++) {
        if (input.hasNextLine()) {
            String insert = input.nextLine();
            for(int x = 0; x < insert.size(); x++) {
                maze[i][x] = insert.charAt(x);
    }Otherwise, only one character per line is read and storing a character actually should fail.

  • Reading data from a text file in to an array

    Ok nobody tell me to search forums, read books, point me to the tutorials, i have done all that and still don't get it. so can some one help me write some code. I would like to read text from a file into an array. The array name is VehilcleList. Simplest was possible would be great. I dont want to use redirection, preferably using the filereader and filewriter class i imagine.

    Your quick example:import java.io.*;
    import java.util.*;
    public class TryReadFileToArray {
        public static void main(String[] args) {
            File file = new File("C:/java/eclipse/workspace/scjp/vehicles.dat");
            ArrayList vehicles = (ArrayList) getVehicles(file);
            for (Iterator i = vehicles.iterator(); i.hasNext(); ) {
                System.out.println(i.next());
        public static List getVehicles(File file) {
            ArrayList vehicles = new ArrayList();
            try {
                BufferedReader buf = new BufferedReader(new FileReader(file));
                while (buf.ready()) {
                    String line = buf.readLine();
                    StringTokenizer tk = new StringTokenizer(line, ",");
                    ArrayList params = new ArrayList();
                    while (tk.hasMoreElements()) {
                        params.add(tk.nextToken());
                    Vehicle v =
                        new Vehicle(
                            (String) params.get(0),
                            (String) params.get(1),
                            (String) params.get(2),
                            Integer.parseInt((String) params.get(3)));
                    vehicles.add(v);                       
            } catch (IOException ioe) {
                System.err.println(ioe);
            } catch (NumberFormatException nfe) {
                System.err.println("Mileage not in correct format: " + nfe);
            return vehicles;
    class Vehicle {
        // flesh out remaining instance members as needed
        private String aMake;
        public Vehicle(
            String aMake,
            String aModel,
            String aRegistrationNumber,
            int aMileage) {
            this.aMake = aMake;
        public String toString() {
            return aMake;
    }Uses the following file (vehicles.dat):Ford,Taurus,105BRQ,55000
    Dodge,Neon,907JZH,105000
    Ferrari,Testarossa,3ATM3,25412

  • Reading data from a text file into a JTextField

    So I am writing a program that will write to and read from a large database. I was hoping to allow a graphical interface for the reading of the data, but I keep getting an error;
    Incompatible Types
    Found: java.lang.string
    Required: javax.swing.JTextField
    Now I know that this means the are incompatible (like trying to give an integer variable a string command) but I can't find any documentation on how to change the String into a JTextField format. I've found several references on how to do the reverse, but with my lack of JAVA knowledge I can't seem to get it to work. (Tried things like getText() and the like, but just end up with more errors).
    *On a side note, is there an easier way to go about reading a file line by line, with each line going into a seperate JTextField, than;
    BufferedReader r;
    try {
    r = new BufferedReader(new FileReader("C:\\temp\\test.txt"));
    while ((thisLine = r.readLine()) != null) {
    array[i] = thisLine;
    i = i + 1
    and then assigning each JTextField it's own array slot?*
    Thank you for your help.

    Try something like this for putting the text in a control:
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    public class Junk{
      String[] s = {"This is String 1.", "This is String 2.", "This is String 3."};
      Junk(){
      public void makeIt(){
        JFrame j = new JFrame("Forum Junk");
        j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel p = new JPanel();
        p.setPreferredSize(new Dimension(300, 200));
        JTextArea jt = new JTextArea();
        p.add(jt);
        j.add(p);
        jt.setText(s[0]);
        jt.append("\n\r"+s[1]);
        jt.append("\n\r"+s[2]);
        j.pack();
        j.setVisible(true);
      public static void main(String[] args) {
        Junk j = new Junk();
        j.makeIt();
    }Depending on your design you may be able to do away with your array and append the text directly to the JTextArray after each line is read.

  • Reading from a text file in to an array, help please

    I have the following
    public class date extends Loans{
    public int dd;
    public int mm;
    public int yyyy;
    public String toString() {
    return String.format( "%d,%d,%d", mm, dd, yyyy );
    public class Loans extends Borrowing {
    public String name;
    public String book;
    public date issue;
    public char type;
    public String toString(){
    return String.format( "%s, %s, %s, %s", name, book, issue, type );
    import java.util.Scanner;
    import java.io.*;
    public class Borrowing extends BorrowingList {
    private Loans[] Loaned = new Loans[20];
    if i want to read in from a text file in to that array how do i do it?

    sorry to keep bothering you and thanks loads for your help but now I am getting the following error mesage
    C:\Documents and Settings\MrW\Menu.java:43: cannot find symbol
    symbol : class IOException
    location: class Menu
    }catch(IOException e){
    Note: C:\Documents and Settings\MrW\Borrowing.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    1 error
    BUILD FAILED (total time: 0 seconds)
    for this line
    }catch(IOException e){                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Reading one line from a text file into an array

    i want to read one line from a text file into an array, and then the next line into a different array. both arays are type string...i have this:
    public static void readAndProcessData(FileInputStream stream){
         InputStreamReader iStrReader = new InputStreamReader (stream);
         BufferedReader reader = new BufferedReader (iStrReader);
         String line = "";          
         try{
         int i = 0;
              while (line != null){                 
                   names[i] = reader.readLine();
                   score[i] = reader.readLine();
                   line = reader.readLine();
                   i++;                
              }catch (IOException e){
              System.out.println("Error in file access");
    this section calls it:
    try{                         
         FileInputStream stream = new FileInputStream("ISU.txt");
              HighScore.readAndProcessData(stream);
              stream.close();
              names = HighScore.getNames();
              scores = HighScore.getScores();
         }catch(IOException e){
              System.out.println("Error in accessing file." + e.toString());
    it gives me an array index out of bounds error

    oh wait I see it when I looked at the original quote.
    They array you made called names or the other one is prob too small for the amount of names that you have in the file. Hence as I increases it eventually goes out of bounds of the array so you should probably resize the array if that happens.

  • Removing the Control Characters from a text file

    Hi,
    I am using the java.util.regex.* package to removing the control characters from a text file. I got below programming from the java.sun site.
    I am able to successfully compile the file and the when I try to run the file I got the error as
    ------------------------------------------------------------------------D:\Debi\datamigration>java Control
    Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repet
    ition
    {cntrl}
    at java.util.regex.Pattern.error(Pattern.java:1472)
    at java.util.regex.Pattern.closure(Pattern.java:2473)
    at java.util.regex.Pattern.sequence(Pattern.java:1597)
    at java.util.regex.Pattern.expr(Pattern.java:1489)
    at java.util.regex.Pattern.compile(Pattern.java:1257)
    at java.util.regex.Pattern.<init>(Pattern.java:1013)
    at java.util.regex.Pattern.compile(Pattern.java:760)
    at Control.main(Control.java:24)
    Please help me on this issue.
    Thanks&Regards
    Debi
    import java.util.regex.*;
    import java.io.*;
    public class Control {
    public static void main(String[] args)
    throws Exception {
    //Create a file object with the file name
    //in the argument:
    File fin = new File("fileName1");
    File fout = new File("fileName2");
    //Open and input and output stream
    FileInputStream fis =
    new FileInputStream(fin);
    FileOutputStream fos =
    new FileOutputStream(fout);
    BufferedReader in = new BufferedReader(
    new InputStreamReader(fis));
    BufferedWriter out = new BufferedWriter(
    new OutputStreamWriter(fos));
         // The pattern matches control characters
    Pattern p = Pattern.compile("{cntrl}");
    Matcher m = p.matcher("");
    String aLine = null;
    while((aLine = in.readLine()) != null) {
    m.reset(aLine);
    //Replaces control characters with an empty
    //string.
    String result = m.replaceAll("");
    out.write(result);
    out.newLine();
    in.close();
    out.close();

    Hi,
    I used the code below with the \p, but I didn't able to complie the file. It gave me an
    D:\Debi\datamigration>javac Control.java
    Control.java:24: illegal escape character
    Pattern p = Pattern.compile("\p{cntrl}");
    ^
    1 error
    Please help me on this issue.
    Thanks&Regards
    Debi
    // The pattern matches control characters
    Pattern p = Pattern.compile("\p{cntrl}");
    Matcher m = p.matcher("");
    String aLine = null;

  • Read data from a text file, one line at a time.

    I need to read data from a text file, and display each line in a String Indicator on Front Panel. It displays each line, but I get Error 4, End Of Line, unless I enter an extra line of data in the file that I don't need. I tried Read From Text File.vi, made by Nat Instr, and it gave the same error.

    The Read from Text File.vi reads data from a text file line by line until the user stops the VI manually with the Stop button on the front panel, or until an error (such as "Error 4, End of file") occurs. If an error occurs, the Simple Error Handler.vi pops up a dialog that tells you which error occurred.
    The Read from Text File.vi uses a while loop, but if you knew how many lines you wanted to read, you could replace the while loop with a for loop set to read that many lines from the file.
    If you need something more dynamic because the number of lines in your files vary, then you could change the code of the Read from Text File.vi to the expect "Error 4, End of file" and handle it appropriately. This would require unbundling the error cluster that comes fro
    m the Read File function with the Unbundle By Name function, so that you can expose the individual error "status" and error "code" values stored in the cluster. If the value of the error "code" is 4, then you can change the error "status" from true to false, and you can rebundle the cluster with the Bundle by Name function. Setting the error "status" to false instructs the Simple Error Handler to ignore the error. Otherwise, pass the original error cluster to the Simple Error Handler.vi, so that you can see what the error is.
    Of course, if you're not interested in what the errors are, you could just remove the Simple Error Handler.vi, but then you wouldn't see any error messages.
    Best of Luck,
    Dieter
    Dieter Schweiss
    Applications Engineer
    National Instruments

  • Need to read data from a text file

    I need to read data from a text file and create my own hash table out of it. I'm not allowed to use the built in Java class, so how would I go implementing my own reading method and hash table class?

    It's not possible to read from a file without using classes from the core API*. You'll have to get clarification from your instructor as to which classes are and are not allowed.
    [http://java.sun.com/docs/books/tutorial/essential/io/]
    *Unless you write a bunch of JNI code to replicate what the java.io classes are doing.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • SQL Loader-How to insert -ve & date values from flat text file into coloumn

    Question: How to insert -ve & date values from flat text file into coloumns in a table.
    Explanation: In the text file, the negative values are like -10201.30 or 15317.10- and the date values are as DDMMYYYY (like 10052001 for 10th May, 2002).
    How to load such values in columns of database using SQL Loader?
    Please guide.

    Question: How to insert -ve & date values from flat text file into coloumns in a table.
    Explanation: In the text file, the negative values are like -10201.30 or 15317.10- and the date values are as DDMMYYYY (like 10052001 for 10th May, 2002).
    How to load such values in columns of database using SQL Loader?
    Please guide. Try something like
    someDate    DATE 'DDMMYYYY'
    someNumber1      "TO_NUMBER ('s99999999.00')"
    someNumber2      "TO_NUMBER ('99999999.00s')"Good luck,
    Eric Kamradt

Maybe you are looking for

  • ITunes 11 / 64 bit and windows 8 / 64 bit

    syncronisation of apps failed ! jump from step 4 to 5 without any action and error messages. please help

  • WWAN Not available in MenuBar

    Hi, I have got an EVDO modem working fine in leopard. I have to open Network preferences every time in order to connect or disconnect it. I dont get either modem or WWAN in Leopard Menu Bar. How do i make it appear is Menu Bar?

  • IPhone device not recognised

    I have had an iPhone for over a year and i have never had any major issues, i also had a mac desktop computer but for christmas i received a macbook pro, i managed to transfer all the information between my old mac and the new one but now when it com

  • Asset master location

    Dear Expert, Please suggest for below mention scenario. client sends Kit (Asset) to different Customer in different location. The property remains with client and depreciation is calculated. We need to capture the address of location where the Kit (A

  • Application Manager failing on new CC install

    hi i just joined CC - and am trying to download Dreamweaver - but am getting an error on the application manager, such as the following: i have seen mention of an uninstaller tool or something - i am wary of using this, as i have a previous version o