Solved

Trouble with getting text file into 2D array

Posted on 2012-03-13
10
272 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
 
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
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

708 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now