Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Trouble with getting text file into 2D array

Posted on 2012-03-13
10
Medium Priority
?
284 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
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!

 
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 2000 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 2000 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

Build and deliver software with DevOps

A digital transformation requires faster time to market, shorter software development lifecycles, and the ability to adapt rapidly to changing customer demands. DevOps provides the solution.

Question has a verified solution.

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

Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses

705 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