Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 285
  • Last Modified:

Trouble with getting text file into 2D array

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
jwhmack
Asked:
jwhmack
  • 8
2 Solutions
 
for_yanCommented:
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
 
for_yanCommented:
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
 
for_yanCommented:
Post your students.txt file and I'll try to debug it
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
for_yanCommented:
You also never increment x or y
0
 
for_yanCommented:
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
 
for_yanCommented:
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
 
for_yanCommented:
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
 
jwhmackAuthor Commented:
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
 
CEHJCommented:
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
 
for_yanCommented:
>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

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 8
Tackle projects and never again get stuck behind a technical roadblock.
Join Now