Page 1 of 2 12 LastLast
Results 1 to 20 of 21
  1. #1
    benn22 is offline Member
    Join Date
    Feb 2011
    Posts
    17
    Rep Power
    0

    Default Store Text-file Into 2D Array

    I am making a game where the party (P) must get to the exit (E) to win the game.

    I've successfully been able to recognize the lines of my text-file, but I am unsure of how to convert this into a 2D array. Consider my code:

    Java Code:
    public class ReadTest{	
    
    	public static void main(String[] args){
    		Scanner file;
    		String line;
    		int count = 0;
    		file = null;
    		
    		try{
    			file = new Scanner(new File("world.txt"));
    			while (file.hasNext()){
    				count++;
    				line = file.nextLine();
    				System.out.println("Line "+count+":"+line);
    			}
    		}catch (Exception e){
    			System.out.println(e.getMessage());
    		}finally{
    			if (file != null)
    				file.close();
    		}
    	}
    }
    This is the following output:



    I understand that I have 10 lines in total, but I wish to split this somehow so it can also have columns to make a 2D array.

    Any help appreciated. Thanks!
    Ben.

  2. #2
    NRitH is offline Senior Member
    Join Date
    Feb 2011
    Posts
    118
    Rep Power
    0

    Default

    Java Code:
        [B]char[][] = new char[10][10];[/B]
        while (file.hasNext()){
            line = file.nextLine();
            [B]char[count] = line.getCharacters();[/B]
            count++;
        }
    The second dimension of the array needs to be the length of each String; I just picked 10 for convenience.

  3. #3
    YolanC is offline Member
    Join Date
    Feb 2011
    Posts
    3
    Rep Power
    0

    Default

    I think this can also be done by using the toCharArray() method of the String class.
    This will return an array of char's for each line of text in your text-document.
    Then you add the given array to your own predefined 2dementional array and go the the next line of text and the next place in your array.
    Repeat.

  4. #4
    NRitH is offline Senior Member
    Join Date
    Feb 2011
    Posts
    118
    Rep Power
    0

    Default

    Quote Originally Posted by YolanC View Post
    I think this can also be done by using the toCharArray() method of the String class.
    This will return an array of char's for each line of text in your text-document.
    Then you add the given array to your own predefined 2dementional array and go the the next line of text and the next place in your array.
    Repeat.
    You're right--I was coding from memory. There is no getCharacters() method on String.

  5. #5
    benn22 is offline Member
    Join Date
    Feb 2011
    Posts
    17
    Rep Power
    0

    Default

    Quote Originally Posted by NRitH View Post
    You're right--I was coding from memory. There is no getCharacters() method on String.
    Yes. I've tested it out and the console reads, "Cannot find symbol". Is there an alternative approach?

    EDIT: Nevermind. When I used toCharArray it seems to be responding. This is the following output:



    I think we're getting close to getting this into a 2D-Array.
    Last edited by benn22; 02-23-2011 at 10:08 PM.

  6. #6
    benn22 is offline Member
    Join Date
    Feb 2011
    Posts
    17
    Rep Power
    0

    Default

    I came up with a different approach. After researching extensively on this, I've come to realize that people are using tokens to come about making their 2D-Array. Here is what I have so far:

    Java Code:
    import java.util.Scanner;
    import java.io.File;
    
    public class ReadTest2{	
    
    	public static void main(String[] args) throws Exception{
    		Scanner file;
    		String line;
    		int count = 0;
    		int j = 0;
    		String[][] grid = new String[10][10];
    		String[] tokens;
    		file = new Scanner(new File("world.txt"));
    		while (file.hasNext()){
    			line = file.nextLine();
    			tokens = line.split("\\s");
    			for (j=0; j<tokens.length; j++){
    				grid[count][j] = tokens[j];
    			}
    			count++;
    		}
    		if (file != null)
    			file.close();
    	}
    }
    When I print grid[count][j], it will show the data vertically. For example:

    Java Code:
    x
    
    P
    
    
    x
    
    x
    
    E
    Note: Not to scale.

    However, this is not the desired output. I want to be able to store my text-file into a 2D-Array so it can be edited via the array.

    The following attachment, world.txt, is provided for view.

    Thank you.
    Ben
    Attached Files Attached Files

  7. #7
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,785
    Rep Power
    7

    Default

    You cannot split on whitespace as your line of text contains spaces that you want to retain. Go back to the original advice and use the toCharArray method.

  8. #8
    benn22 is offline Member
    Join Date
    Feb 2011
    Posts
    17
    Rep Power
    0

    Default

    Taking Junky's advise, I've reverted back to using toCharArray rather than tokens. Here is how my code looks so far:

    Java Code:
    import java.util.Scanner;
    import java.io.File;
    
    public class ReadTest2{	
    
    	public static void main(String[] args) throws Exception{
    		Scanner file;
    		String line;
    		int count = 0;
    		int j = 0;
    		char[][] grid = new char[10][10];
    		file = new Scanner(new File("world.txt"));
    		while (file.hasNext()){
    			line = file.nextLine();
    			grid[count] = line.toCharArray();
    			count++;
    		}
    		if (file != null)
    			file.close();
    	}
    }
    When I print grid[count] it will show world.txt successfully with no problems. I've been using a lot of nested for-loops to come attain my 2D-Array, but I've been running across a lot of messages regarding 'incompatible types'.

    Thanks for your support guys.
    Ben.

  9. #9
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,785
    Rep Power
    7

    Default

    but I've been running across a lot of messages regarding 'incompatible types'.
    We don't read minds. Ask a specific question. If it relates to an error then copy and paste the EXACT error as well as the code that it relates to.

  10. #10
    benn22 is offline Member
    Join Date
    Feb 2011
    Posts
    17
    Rep Power
    0

    Default

    Good news. I successfully managed to put everything into chars, but it won't print exactly as depicted in the text file. Here is my code:

    Java Code:
                    ...
    		char[][] grid = new char[10][10];
    		char[] temp;
    		file = new Scanner(new File("world.txt"));
    		while (file.hasNext()){
    			line = file.nextLine();
    			temp = line.toCharArray(); 
    			for (j=0; j<temp.length; j++){
    				grid[count][j] = temp[j];
    				System.out.print(grid[count][j]);
    			}
    			count++;
    		}
                    ...
    The following is displayed:



    If I were to print using .println it will be vertically printed and would also print horizontally if I were to use .print.

    I feel that I am very close to putting this into a 2D-Array.

    Thanks for any help.
    Ben

  11. #11
    NRitH is offline Senior Member
    Join Date
    Feb 2011
    Posts
    118
    Rep Power
    0

    Default

    Put a System.out.println() at the end of that while loop.

  12. #12
    benn22 is offline Member
    Join Date
    Feb 2011
    Posts
    17
    Rep Power
    0

    Default

    Quote Originally Posted by NRitH View Post
    Put a System.out.println() at the end of that while loop.
    I wish it was that simple, but since I am printing grid[count][j] outside of the for-loop, j is not within the iteration so this message is displayed:



    I've run across something called a StringTokenizer which evidentially puts them into stacks, but how would I come about parsing 'char' characters like that? I don't think Java has an API for parseChar. However, I don't think this should be that complex. There has to be a clean, clear-cut method of how to approach this.

    Thanks.
    Ben

  13. #13
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    Man, this is a lot of back and forth. Remind me why you aren't just reading the file line by line, then adding each character to a 2D array using lineFromFile.charAt(index) to populate?

    All this talk of tokenizing and parsing and what-not. Am I understanding you correctly in that you have a text file with a 'map' and you want to load it into a corresponding 2D array of chars?

  14. #14
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,785
    Rep Power
    7

    Default

    They don't even need to use charAt.
    Java Code:
    grid[x] = line.toCharArray();

  15. #15
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    Right, thanks, I read right over that somehow. Either way, its a very simple problem/solution. A 2D array is an array of Arrays. So if you get an array for each line, you can simply copy its contents into the collection of arrays (your 2D array).

  16. #16
    NRitH is offline Senior Member
    Join Date
    Feb 2011
    Posts
    118
    Rep Power
    0

    Default

    Quote Originally Posted by benn22 View Post
    I wish it was that simple, but since I am printing grid[count][j] outside of the for-loop, j is not within the iteration so this message is displayed:



    I've run across something called a StringTokenizer which evidentially puts them into stacks, but how would I come about parsing 'char' characters like that? I don't think Java has an API for parseChar. However, I don't think this should be that complex. There has to be a clean, clear-cut method of how to approach this.

    Thanks.
    Ben
    NO, I mean an empty println().

  17. #17
    benn22 is offline Member
    Join Date
    Feb 2011
    Posts
    17
    Rep Power
    0

    Default

    I'm dropping this method of approach for now. Instead, I have hard-coded the grid without reading from a file. This is how I have done this:

    Java Code:
    public class Forest{
    
    	public static final int SIZE = 10;
    	char[][] grid = new ForestItem[SIZE][SIZE];
    			
    	public Forest(){
    		for (int i=0; i<grid.length; i++){
    			for (int j=0; i<grid[i].length; j++)
    				grid[i][j] = null;
    		}
    		
    		grid[0][9] = new ForestItem('x');
    		grid[1][1] = new ForestItem('P');
    		grid[6][9] = new ForestItem('x');
    		grid[7][6] = new ForestItem('x');	
    		grid[8][3] = new ForestItem('x');
    		grid[9][9] = new ForestItem('E');		
    		
    	public void display(){
    		for (int i=0; i<grid.length; i++){
    			for (int j=0; i<grid[i].length; j++)
    				if (grid[i][j] != null)
    					System.out.println(grid[i][j].getAppearance());
    				else
    					System.out.print(" ");
    		}
    	}
    }
    Sorry for all the trouble. Once I have more experience with Java, I will most likely attempt this method again.
    Ben

  18. #18
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,785
    Rep Power
    7

    Default

    Well that is not a very good attitude. You have been given plenty of advice to enable you to finish this.

    That last code you posted doesn't compile. The method is inside the constructor.

  19. #19
    benn22 is offline Member
    Join Date
    Feb 2011
    Posts
    17
    Rep Power
    0

    Default

    Quote Originally Posted by Junky View Post
    That last code you posted doesn't compile. The method is inside the constructor.
    The file ReadTest2 I've been using was to test on how to implement a text to a 2D-Array. The last code I've posted is part of 6 adjacent files that work as a linked-list. Due to time constraints, I have to finish other parts of the code instead of worrying about a 2D-Array issue. Perhaps when I have surplus time, I will try to read from file and revive this thread again.
    Ben

  20. #20
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    I'm dropping this method of approach for now
    So what you're saying is, you're not listening to any of the advice which would lead to something like a 3 line of code solution, and are instead, nailing your feet to the floor. Good luck with that.

Page 1 of 2 12 LastLast

Similar Threads

  1. store data into an array from a file
    By chopo1980 in forum New To Java
    Replies: 10
    Last Post: 11-13-2009, 09:48 AM
  2. Replies: 4
    Last Post: 04-10-2009, 05:35 AM
  3. how to store string in text file
    By santhosh_el in forum AWT / Swing
    Replies: 2
    Last Post: 04-03-2009, 06:21 AM
  4. Replies: 3
    Last Post: 04-07-2008, 06:02 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •