Results 1 to 18 of 18
Like Tree1Likes
  • 1 Post By Norm

Thread: 2d array - elegant population?

  1. #1
    Redefine12 is offline Member
    Join Date
    Feb 2012
    Posts
    66
    Rep Power
    0

    Default 2d array - elegant population?

    Hey all.
    I've seen other threads here regarding populating a 2d array from a text file. The difference here, is I'm trying to go for what I think is a more elegant approach. I'd like some input, specifically on the looping I'm using in the class I'll post below. The portion I'd like to use is commented out, while the
    Java Code:
    data[row][col] = "item " + (row*cols + col + 1);
    portion is what I'm using to fill the array/JTable with dummy data.

    When I comment out above and use the while loop instead, I don't receive an error of any kind at run time, it simply hangs and does nothing. Any constructive help with this loop is appreciated.

    Here's the dummy text file contents:

    0134S 51S5S1S 2315561 15263122F qwer qwe
    0ES DDD5S1S 2315561 15263122F qwer qwe
    01AS 51S5S1S 2316Y561 15263122F qwer qwe
    SDAS 51S5S1S 2315561 1526316Y6Y qwer qwe
    01AS 51S4F1S 23SD561 15263122F qwer qwe

    Here's my getTable:

    Java Code:
     private JTable getTable() throws IOException
        {
            
            String[] colNames = { "ECN", "CUSTOMER", "MODEL", "SERIAL", "ICN", "MFR_CD" };
            int rows = 32, cols = colNames.length;
            Object[][] data = new Object[rows][cols];
            FileInputStream fin =  new FileInputStream("C:\\INV\\TEST.txt");
            BufferedReader br = new BufferedReader(new InputStreamReader(fin));
    
            String aLine;
    		for(int row = 0; row < rows; row++)
                for(int col = 0; col < cols; col++){
                    data[row][col] = "item " + (row*cols + col + 1);
                	/*
                    while ((aLine = br.readLine()) != null) {
                        StringTokenizer st2 = new StringTokenizer(aLine, " ");
                        while(st2.hasMoreTokens())
                        data[row][col] = st2;
     
                    }
                    */
                }
            
            DefaultTableModel model = new DefaultTableModel(data, colNames)
            {
                public Class getColumnClass(int col)
                {
                    Object o = getValueAt(0, col);
                    if(o == null)
                        return Object.class;
                    else
                        return o.getClass();
                }
            };
            
            JTable table = new JTable(model);
            table.setDefaultRenderer(String.class, new CustomRenderer());
            table.setRowSelectionAllowed(true);
            table.setColumnSelectionAllowed(true);
            table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            return table;
        }
    Last edited by Redefine12; 03-16-2012 at 11:47 PM.

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default Re: 2d array - elegant population?

    It's the while loop that's causing a problem, right?

    In that case, remove the comments and comment out the data[row][col]=... line.

    it simply hangs and does nothing
    I don't think it's doing nothing. The inner while loop looks like it is continually (and forever) assigning the value of st2 to data[row][col].

    Is the commented out while loop supposed to be within the nested for loops? I ask because the while loop reads right until the end of the file and so will only effectively "run" once - but you end up pointlessly entering the loop row*col times by putting it within the for loops.

    Trace through the code, line by line, to see what happens as it processes a file. Notice, especially, when (and if) row and col are incremented. And when assignment to the data array elements takes place.

    I recommend using braces: even with single line blocks of code.

  3. #3
    Redefine12 is offline Member
    Join Date
    Feb 2012
    Posts
    66
    Rep Power
    0

    Default Re: 2d array - elegant population?

    Quote Originally Posted by pbrockway2 View Post
    It's the while loop that's causing a problem, right?
    Yes. I need a push to help begin conceptualizing how to the process of populate the 2d array.

    I'm attempting to follow your reccomendation of steppin through the loop, as well as using brackets to visualize the looping.

    So I initialize row and col int's to 0. I set up the first while loop- while the buffered reader has more to read, and while there are more tokens, assign the token to the row/col and increment row/col.

    Here is where I am:

    Java Code:
    
        private JTable getTable() throws IOException    { 
        	String[] colNames = { "ECN", "CUSTOMER", "MODEL", "SERIAL", "ICN", "MFR_CD" };  
        	int rows = 32, cols = colNames.length;    
        	Object[][] data = new Object[rows][cols];    
        	FileInputStream fin =  new FileInputStream("C:\\INV\\TEST.txt");
        	BufferedReader br = new BufferedReader(new InputStreamReader(fin)); 
        	String aLine;    
        	
        	/*
        	for(int row = 0; row < rows; row++)     
        		for(int col = 0; col < cols; col++){    
        			data[row][col] = "test " + (row*cols + col + 1);   
        		}
        	*/		
        	
        	int row = 0;
        	int col = 0;
        		while ((aLine = br.readLine()) != null) {       
        			StringTokenizer st2 = new StringTokenizer(aLine, " "); 
        			while(st2.hasMoreTokens()){       
        			    data[row][col] = st2.toString();    
        			row ++;
        			col++;
        			}
        			}      
    
        	DefaultTableModel model = new DefaultTableModel(data, colNames) 
        	{            public Class getColumnClass(int col)     
        	{                Object o = getValueAt(0, col);     
        	if(o == null)                 
        		return Object.class;         
        	else              
        		return o.getClass();   
        	}     
        	};    
        	JTable table = new JTable(model);     
        	table.setDefaultRenderer(String.class, new CustomRenderer());
        	table.setRowSelectionAllowed(true);       
        	table.setColumnSelectionAllowed(true);     
        	table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 
        	return table;   
        	}

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,224
    Rep Power
    20

    Default Re: 2d array - elegant population?

    Java Code:
    data[row][col] = st2.toString();
    I think you need to have a look at the API for StringTokenizer.
    Of course, you ought to note the last para in the class description:
    "
    StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
    "
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  5. #5
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,882
    Rep Power
    25

    Default Re: 2d array - elegant population?

    Why are you assigning the StringTokenizer's reference value to the array instead of the nextToken's value?
    If you don't understand my response, don't ignore it, ask a question.

  6. #6
    Redefine12 is offline Member
    Join Date
    Feb 2012
    Posts
    66
    Rep Power
    0

    Default Re: 2d array - elegant population?

    Quote Originally Posted by Tolls View Post
    StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
    "
    Thanks. I was using StringTokenizer for the hasNext() method it contains, largely due to my lack of being able to grasp how to set up the necessary loop to create the array. I've modified, using split, but am still getting unusable results (array coordinates printing to fields of the JTable).

    I'd really appreciate some direction on setting up the logic of the loop. I know what I have is wrong, but can't seem to get my head around the loop logic required.

    Java Code:
       private JTable getTable() throws IOException    { 
        	String[] colNames = { "ECN", "CUSTOMER", "MODEL", "SERIAL", "ICN", "MFR_CD" };  
        	int rows = 32, cols = colNames.length;    
        	Object[][] data = new Object[rows][cols];    
        	FileInputStream fin =  new FileInputStream("C:\\INV\\TEST.txt");
        	BufferedReader br = new BufferedReader(new InputStreamReader(fin)); 
        	String aLine;    
        	
        	/*
        	for(int row = 0; row < rows; row++)     
        		for(int col = 0; col < cols; col++){    
        			data[row][col] = "test " + (row*cols + col + 1);   
        		}
        	*/		
        	
        		while ((aLine = br.readLine()) != null) {       
        			//StringTokenizer st2 = new StringTokenizer(aLine, " "); 
        			String[] val = aLine.split(" ");
        	    	for(int row = 0; row < rows; row++)     
        	    		for(int col = 0; col < cols; col++){    
        	    			data[row][col] = val;
    
        			row ++;
        			col++;
        			}
        			}      
    
        	DefaultTableModel model = new DefaultTableModel(data, colNames) 
        	{            public Class getColumnClass(int col)     
        	{                Object o = getValueAt(0, col);     
        	if(o == null)                 
        		return Object.class;         
        	else              
        		return o.getClass();   
        	}     
        	};    
        	JTable table = new JTable(model);     
        	table.setDefaultRenderer(String.class, new CustomRenderer());
        	table.setRowSelectionAllowed(true);       
        	table.setColumnSelectionAllowed(true);     
        	table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 
        	return table;   
        	}

  7. #7
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,882
    Rep Power
    25

    Default Re: 2d array - elegant population?

    val is an array. You need to use an index to get its contents:
    val[ix]
    Start ix at 0 and increment it after each use. Test that its value does not go past the end of the array.
    If you don't understand my response, don't ignore it, ask a question.

  8. #8
    Redefine12 is offline Member
    Join Date
    Feb 2012
    Posts
    66
    Rep Power
    0

    Default Re: 2d array - elegant population?

    Thank you, Norm for your index tip! I'm now getting data into the data[][]. However, the data does not populate in the manner I would expect. The file is formatted as follows:

    0134S 51S5S1S 2315561 15263122F qwer qwe
    0ES DDD5S1S 2315561 15263122F qwer qwe
    01AS 51S5S1S 2316Y561 15263122F qwer qwe
    SDAS 51S5S1S 2315561 1526316Y6Y qwer qwe
    01AS 51S4F1S 23SD561 15263122F qwer qwe


    My JTable, is populating as follows:

    ECN CUSTOMER MODEL SERIAL ICN MFR_CD

    01AS
    01AS
    01AS


    .
    .
    etc.

    I believe I am close here...

    Java Code:
     private JTable getTable() throws IOException    { 
        	String[] colNames = { "ECN", "CUSTOMER", "MODEL", "SERIAL", "ICN", "MFR_CD" };  
        	int rows = 32, cols = colNames.length;    
        	Object[][] data = new Object[rows][cols];    
        	FileInputStream fin =  new FileInputStream("C:\\INV\\TEST.txt");
        	BufferedReader br = new BufferedReader(new InputStreamReader(fin)); 
        	String aLine;    
        	//TRY 1
        	/*
        	for(int row = 0; row < rows; row++)     
        		for(int col = 0; col < cols; col++){    
        			data[row][col] = "test " + (row*cols + col + 1);   
        		}
        	*/
        	//TRY 2
        	
        		while ((aLine = br.readLine()) != null) {       
        			//StringTokenizer st2 = new StringTokenizer(aLine, " "); 
        			String[] val = aLine.split(" ");
        			int index = 0;
        	    	for(int row = 0; row < rows; row++)     
        	    		for(int col = 0; col < cols; col++){    
        	    			data[row][col] = val[index];    	    			
        			row ++;
        			col++;
        			}index ++;
        			}      
    		
        	DefaultTableModel model = new DefaultTableModel(data, colNames) 
        	{            public Class getColumnClass(int col)     
        	{                Object o = getValueAt(0, col);     
        	if(o == null)                 
        		return Object.class;         
        	else              
        		return o.getClass();   
        	}     
        	};    
        	JTable table = new JTable(model);     
        	table.setDefaultRenderer(String.class, new CustomRenderer());
        	table.setRowSelectionAllowed(true);       
        	table.setColumnSelectionAllowed(true);     
        	table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 
        	return table;   
        	}

  9. #9
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,882
    Rep Power
    25

    Default Re: 2d array - elegant population?

    data does not populate in the manner I would expect.
    Show what you are getting and explain what is wrong with it and show how you want it to be.
    Use the Arrays class's deepToString() method to format the array for printing using println after done filling the array.
    Last edited by Norm; 03-19-2012 at 09:13 PM.
    If you don't understand my response, don't ignore it, ask a question.

  10. #10
    Redefine12 is offline Member
    Join Date
    Feb 2012
    Posts
    66
    Rep Power
    0

    Default Re: 2d array - elegant population?

    I'm getting:

    01AS
    01AS
    01AS
    01AS
    01AS
    01AS
    01AS
    01AS
    01AS
    01AS
    01AS
    01AS
    01AS
    01AS
    01AS

    And expecting:


    0134S 51S5S1S 2315561 15263122F qwer qwe
    0ES DDD5S1S 2315561 15263122F qwer qwe
    01AS 51S5S1S 2316Y561 15263122F qwer qwe
    SDAS 51S5S1S 2315561 1526316Y6Y qwer qwe
    01AS 51S4F1S 23SD561 15263122F qwer qwe

    *EDIT: When I copy/paste what I'm getting it removes whitespace and prints all under the first 'column'. It's printing the '01AS' string diagonally across every other column.

  11. #11
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,882
    Rep Power
    25

    Default Re: 2d array - elegant population?

    It looks like you are not incrementing the index for the source array and are copying the same thing into all the elements.
    Check the code that you are incrementing the index for the source array immediately after you use it and not outside of the loop.
    If you don't understand my response, don't ignore it, ask a question.

  12. #12
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,882
    Rep Power
    25

    Default Re: 2d array - elegant population?

    To see what is in the 2D array: Use the Arrays class's deepToString() method to format the array for printing using println after done filling the array.
    If you don't understand my response, don't ignore it, ask a question.

  13. #13
    Redefine12 is offline Member
    Join Date
    Feb 2012
    Posts
    66
    Rep Power
    0

    Default Re: 2d array - elegant population?

    I've completely updated my approach and now have the 2d array populating correctly. My next hurdle is displaying a JTable with ONLY the ammount of rows found in the file I'm scanning. I can use colNames.length; for the columns, but because I haven't yet scanned the file when I create the Object[][] data, I have to pre-set my int rows variable. Any way around this? Here's where I'm at:

    Java Code:
    
        private JTable getTable() throws IOException    { 
        	Scanner s = new Scanner(new File("C:\\INV\\TEST4.txt")); 
        	String[] colNames = { "ECN", "CUSTOMER", "MODEL", "SERIAL", "ICN", "MFR_CD" };  
        	int rows = 1000, cols = colNames.length;    
        	Object[][] data = new Object[rows][cols];    
        	
        	//TRY 1
        	/*
        	for(int row = 0; row < rows; row++)     
        		for(int col = 0; col < cols; col++){    
        			data[row][col] = "test " + (row*cols + col + 1);   
        		}
        	*/
    
        	//TRY 2
        	  
    		List<String[]> list = new ArrayList<String[]>();      
    		while (s.hasNextLine()) {         
    			String[] line = s.nextLine().split(" ");   
    			list.add(new String[] { (line[0]),   
    									(line[1]),
    									(line[2]),
    									(line[3]),
    									(line[4]),
    									(line[5])
    			
    									});      
    			}         
    		int numberOfRows = list.size();    
    		int numberOfColumns = 6; 
    		
    		for (int i = 0; i < numberOfRows; i++) {        
    			data[i] = list.get(i);     
    		}     
    		
        	
        	DefaultTableModel model = new DefaultTableModel(data, colNames) 
        	{            public Class getColumnClass(int col)     
        	{                Object o = getValueAt(0, col);     
        	if(o == null)                 
        		return Object.class;         
        	else              
        		return o.getClass();   
        	}     
        	};    
        	JTable table = new JTable(model);     
        	table.setDefaultRenderer(String.class, new CustomRenderer());
        	table.setRowSelectionAllowed(true);       
        	table.setColumnSelectionAllowed(true);     
        	table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 
    
        	return table;   
        	
        	
        	}

  14. #14
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,882
    Rep Power
    25

    Default Re: 2d array - elegant population?

    Do you need to give data a value before you fill it?
    At line 29 you know the number of rows. Assign it a value there.
    If you don't understand my response, don't ignore it, ask a question.

  15. #15
    Redefine12 is offline Member
    Join Date
    Feb 2012
    Posts
    66
    Rep Power
    0

    Default Re: 2d array - elegant population?

    I believe I do need to know. I tried creating int rows; without initializing, setting int rows = 0;, waiting to assign it until row 29 etc etc, all receive compilation errors. "The local variable may not have been initialized"

  16. #16
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,882
    Rep Power
    25

    Default Re: 2d array - elegant population?

    Did you try defining it at line 29?
    Redefine12 likes this.
    If you don't understand my response, don't ignore it, ask a question.

  17. #17
    Redefine12 is offline Member
    Join Date
    Feb 2012
    Posts
    66
    Rep Power
    0

    Default Re: 2d array - elegant population?

    I seee. The trick was to wait to create the Object[][] data = new Object[rows][cols]; AFTER the data has been scanned, not just the assignment of the rows variable.. Thanks for the push!

    Java Code:
    
        private JTable getTable() throws IOException    { 
        	Scanner s = new Scanner(new File("C:\\INV\\TEST4.txt")); 
        	String[] colNames = { "ECN", "CUSTOMER", "MODEL", "SERIAL", "ICN", "MFR_CD" };  
        	 int cols = colNames.length;    
    
        	//TRY 1
        	/*
        	for(int row = 0; row < rows; row++)     
        		for(int col = 0; col < cols; col++){    
        			data[row][col] = "test " + (row*cols + col + 1);   
        		}
        	*/
    
        	//TRY 2
        	  
    		List<String[]> list = new ArrayList<String[]>();      
    		while (s.hasNextLine()) {         
    			String[] line = s.nextLine().split(" ");   
    			list.add(new String[] { (line[0]),   
    									(line[1]),
    									(line[2]),
    									(line[3]),
    									(line[4]),
    									(line[5])
    			
    									});      
    			}         
    		
    		int rows = list.size();
    		int numberOfColumns = 6; 
    		
        	Object[][] data = new Object[rows][cols];    
    		for (int i = 0; i < rows; i++) {        
    			data[i] = list.get(i);     
    		}     
    		
        	DefaultTableModel model = new DefaultTableModel(data, colNames) 
        	{            public Class getColumnClass(int col)     
        	{                Object o = getValueAt(0, col);     
        	if(o == null)                 
        		return Object.class;         
        	else              
        		return o.getClass();   
        	}     
        	};    
        	JTable table = new JTable(model);     
        	table.setDefaultRenderer(String.class, new CustomRenderer());
        	table.setRowSelectionAllowed(true);       
        	table.setColumnSelectionAllowed(true);     
        	table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 
    
        	return table;   
        	
        	}

  18. #18
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,882
    Rep Power
    25

    Default Re: 2d array - elegant population?

    You're welcome.
    If you don't understand my response, don't ignore it, ask a question.

Similar Threads

  1. Help writing a program to study population growth
    By westerbamos in forum New To Java
    Replies: 2
    Last Post: 02-12-2012, 11:26 PM
  2. Replies: 0
    Last Post: 05-12-2011, 08:04 PM
  3. Replies: 23
    Last Post: 09-07-2010, 09:12 PM
  4. Replies: 2
    Last Post: 09-06-2010, 02:03 AM
  5. Combo Box Population
    By barusk in forum Java Applets
    Replies: 1
    Last Post: 03-20-2009, 02:48 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
  •