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
Solved

Trouble with getting text file into 2D array

Posted on 2012-03-13
10
275 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
Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

 
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

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
simple java question 3 59
oracle 11g 23 106
String array comparison 4 38
Need Help! Getting a syntax error and don't understand why 3 31
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
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…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

792 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