Solved

Trouble with getting text file into 2D array

Posted on 2012-03-13
10
274 Views
Last Modified: 2012-03-13
I have been searching the posts but can't find enough help within them to get me over the hump here.  I have a text file that that I am trying to read into a 2D array.  The first line has the number of records in the file and the remaining lines look like this:
111111  NAME  NAME  TITLE  00.0  0.00
Each separation is a new column in the array but they can be entered as String, there is no need for the numbers to come in as integers or doubles (with the exception of the very first line that contains the number of records in the file).  I have been working on this for days and cannot seem to figure this out.  When I run this code I don't get any errors but what happens with this test at the end is "This is a test null" and what I expect to see is "This is a test Senior."  Obviously my array is empty but I am not sure why.  This is my code:

import java.io.*;
import java.util.*;

public class TestProgram
{
   public static void main(String args[])
     {
        try
        {
	BufferedReader in = new BufferedReader(new FileReader("students.txt"));
		int x=0, y=0, row = 0;
		row = Integer.parseInt(in.readLine());
		String line;
		String[][] students = new String[row][6];
		while ((line = in.readLine()) != null)	
		{
		   String[] values = line.split("  ");

                           for (String str : values)
	        	   {
	        	     students[x][y]=str;
	         	   }
		}

            in.close();
            System.out.println("This is a test " + students[3][3]);

            }catch( IOException ioException ) {}
     }

}

Open in new window

0
Comment
Question by:jwhmack
  • 8
10 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 37717053
You are printing "This is a test " + students[3][3]

but your students arary is out of scope at this palce you sghould declare studesnts array aas an onstance variable not within the redaing loop
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37717056
try this way:

import java.io.*;
import java.util.*;

public class TestProgram
{
   public static void main(String args[])
     {
String[][] students; 

        try
        {
	BufferedReader in = new BufferedReader(new FileReader("students.txt"));
		int x=0, y=0, row = 0;
		row = Integer.parseInt(in.readLine());
		String line;
		students = new String[row][6];
		while ((line = in.readLine()) != null)	
		{
		   String[] values = line.split("  ");

                           for (String str : values)
	        	   {
	        	     students[x][y]=str;
	         	   }
		}

            in.close();
            System.out.println("This is a test " + students[3][3]);

            }catch( IOException ioException ) {}
     }

}
                                  

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 37717063
Post your students.txt file and I'll try to debug it
0
Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

 
LVL 47

Expert Comment

by:for_yan
ID: 37717089
You also never increment x or y
0
 
LVL 47

Assisted Solution

by:for_yan
for_yan earned 500 total points
ID: 37717112
try this code:

import java.io.*;
import java.util.*;

public class TestProgram
{
   public static void main(String args[])
     {
String[][] students;

        try
        {
	BufferedReader in = new BufferedReader(new FileReader("students.txt"));
		int x=0, y=0, row = 0;
		row = Integer.parseInt(in.readLine());
		String line;
		students = new String[row][6];
		while ((line = in.readLine()) != null)
		{
		   String[] values = line.split("[\\s]+");

                           y=0;

                           for (String str : values)
	        	   {
                       //System.out.println("str: " + str);
	        	     students[x][y]=str;
                       y++;
	         	   }

            x++;
		}

            in.close();
            System.out.println("This is a test " + students[3][3]);

            }catch( IOException ioException ) {}
     }

}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 37717118
The above code with this input file students.txt

5
111111  NAME  NAME  TITLE  00.0  0.00
111111  NAME  NAME  TITLE  00.0  0.00
111111  NAME  NAME  TITLE  00.0  0.00
111111  NAME  NAME  TITLE  00.0  0.00
111111  NAME  NAME  TITLE  00.0  0.00

Open in new window


gives this result:

This is a test TITLE

Open in new window

0
 
LVL 47

Accepted Solution

by:
for_yan earned 500 total points
ID: 37717135
So your code had number of issues:

1) you tried to use array students out opf scope of its ddeclatain
I declaread it immediately in the main() so that its scope becomes the whole method

2) you were assigning    students[x][y]=str;
all the time to students[0][0] because x and y were not being incremneneted after assignemnt

3) method split(..) uses regexpression
if you split by any number of spaces or tabs you need to provide adequate regex
(see the one I put in the code)

I think those were the main issues; try to run this code with your real file
and see if youi get the output you want
0
 

Author Closing Comment

by:jwhmack
ID: 37717200
Bingo, that was it.  I thought my code seemed a bit simple.  Thank you.  I had originally had th array in the main but I couldn't get the row variable to work like I said but it didn't occur to me to just initialize in the main and then call it again inside the try.  I am still learning on a lot of this stuff as you can tell.  Java is definitely a weak spot for me.  So is the \\s for spaces and if I had only had a single space between the values would I have used \s instead of \\s?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 37717265
Each separation is a new column in the array but they can be entered as String, there is no need for the numbers to come in as integers or doubles (with the exception of the very first line that contains the number of records in the file).

There's not much point in representing them as type String since they are clearly not strings in some cases. You should really have them as an array of beans, or failing that (and something you should really avoid) as Object[][]
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37717305
>So is the \\s for spaces and if I had only had a single space between the values would I have used \s instead of \\s?

No, that is not true "\s" will just cause compiler error in this case

Regular Expressions is a big topic - you can start reading about them
here:
http://www.regular-expressions.info/

or about some detials of Java implementation here:

http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html

On the other hand be prepared to spend some significant time on this subject, so if you are now studying java just take for granted some simple expresssion like the one in your code above, and when you have some time later spend it on studying RegEx specifically.
This expression will allow you to split the line into items seprated by one as well as by more than one spaces.
0

Featured Post

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

785 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question