Hi all, this is my codes.

import java.io.*;

public class Testing3
{

	static double[][] mydouble;
    static int a, b;
    static double d;
	static String[] temp;

	public static void main(String args[]) throws Exception
	{

		try
        {
            BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\Serene\\Documents\\Major Project\\Alignment Algorithms\\Testing2.txt"));	//reading files in specified directory

            String str, output="";
            while ((str = in.readLine()) != null)	//file reading
            {
				output += str;
				temp = str.split(",");


                for (String s : temp)
                {

                	d = Double.parseDouble(s);
					mydouble[a][b] = d;
					System.out.println(mydouble[a][b]);



                	for(a=0; a<mydouble.length; a++)
					{

						for(b=0; b<mydouble[a].length; b++)
                    	{

							System.out.println(mydouble[a][b]);
						}

					}
                }

			

            }
            in.close();

            System.out.print(output);


        }catch( IOException ioException ) {}

	}

}

I'm having this error:

Exception in thread "main" java.lang.NullPointerException
at Testing3.main(Testing3.java:29)

I actually read my str from a text file and then parse it. After parsing it, I need to store the parsed numbers into a 2D array just like how it looks like in the original text file. I think the 2D array is empty, as after parsing it, the output printed out is individually. May I know how to I store it properly into the 2D array? As this won't be the only text file I'm going to read, hence how do I indicate the numbers of rows and columns, which will then be the size of the 2D array?

Recommended Answers

All 28 Replies

Your error occurs in line 29 where you attempt to access mydouble[a] but you have never initialize mydouble array? This is one of the part that Java spoils those who learn how to program it. The problem is that Java initiates a value to primitive, so some new people assume that it would be the same for array. It is not!

mydouble = new double[x][y]; // where x and y are integer of the size

If you are working on dynamic array, use ArrayList or something else. The array you are using is not working in your dynamic assignment.

So I have to store my output into arrayList?

Yes, because an array is a fixed size List while an ArrayList is dynamic (it can grow in size).

As Taywin has posted, you need to set the boundaries of an array before you can use it or add elements to it. So the limitation is that you need to know the boundaries first before you can create your array.

And I assume that since you dont know the size of your file at the beginning of your program, ArrayList is preferred.

But I need to do a file read first. So how to I add it to my arrayList?

The file read has nothing to do with the array:

while ((str = in.readLine()) != null) //file reading
{
     myArray.add(Double.parseDouble(str));
}

adds all the doubles it can parse without errors to myArray (ArrayList)

while (true)
{
     myArray.add(Math.Random());
}

adds random doubles to the myArray for ever, the adding is nothing to do with the reading. To check you are reading correctly, just System.out.print(str);

Okay thank you people. I will try it and see if it works! (:

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

public class Testing3
{
	static ArrayList myDouble = new ArrayList();
	//static double[][] myDouble;
    static int a, b;
    static double d;
	static String[] temp;

	public static void main(String args[]) throws Exception
	{

		try
        {
            BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\Serene\\Documents\\Major Project\\Alignment Algorithms\\Testing2.txt"));	//reading files in specified directory

            String str, output="";
            while ((str = in.readLine()) != null)	//file reading
            {
				//output += str;
				temp = str.split(",");

				myDouble.add(Double.parseDouble(str));
}
            in.close();


        }catch( IOException ioException ) {}

	}

}

I have an error that says:

Exception in thread "main" java.lang.NumberFormatException: For input string: "1.0, 2.0, 3.0, 4.0, 5.0"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1224)
at java.lang.Double.parseDouble(Double.java:510)
at Testing3.main(Testing3.java:25)

"1.0, 2.0, 3.0, 4.0, 5.0"

is the input string, the Double.parseDouble(str) only accepts input along the lines of XXXXX.XXXXXX, not multiple doubles, you will have to "split" the string, around the comma then parse the split strings, take a look at:

http://www.rgagnon.com/javadetails/java-0438.html

(I always use that page when i forget how to split strings) that will return an array, go through the array with a for loop and parse the doubles!

OR

save the file in a format that is one double per line (assuming you have control over that!)

Well in line 23 you are splitting str and putting it in the String array temp

temp = str.split(",");

So your temp array will hold the values [1.0,2.0,3.0,4.0,5.0]

But in line 25 you are parsing str to double.

myDouble.add(Double.parseDouble(str));

Instead of parsing the whole String str, do a for loop for all the values in your temp array then parse each element to double then add it into your arrayList

If its not clear, just ask and I will clarify it (",)

Hope this helps.

Hi Eric, what do you mean by parsing it in a for loop? How do I do that?

have you used for loops before? Here is an example that adds up all the integers in a string array:

String[] stringArray = { "4","5","8" };
int total = 0;
for (int i = 0 ; i < stringArray.length ; i++)
{
    total += Integer.parseInt(stringArray[i]);
}
System.out.println("total: " + total);

Okay thank you. People, do you guys know how to read the text file, and then find out the number of rows and columns in the text file? Because I need to know the size (number of rows and columns) before I can do anything.

well, you can find out how many lines (rows) by calling .size() after you have read all your lines into the ArrayList. The number of columns will be the size of the split array from each line.

Why do you need to know this before you read the file?

You could just loop through each line, counting (instead of filling an array) to get the row number (and read the first line and split arround ',' to get the columns) if you need it to be seperate from reading, but it makes sence to just work them out afterwards

Okay I have a problem now. I need to change the way I want it to be.
Firstly, I want to read the text file, then store all my numbers in the text file into a 2D array.
Secondly, after storing them in a 2D array, then I parse them.

May I know how to do that?

Okay I have a problem now. I need to change the way I want it to be.
Firstly, I want to read the text file, then store all my numbers in the text file into a 2D array.
Secondly, after storing them in a 2D array, then I parse them.

May I know how to do that?

Do you mean that the first 2D array will have the values of the file as Strings and then you will loop the array?

In case you have most of the code. I will post part of what you have done with some suggestions. You must remember first that you can add whatever you want in ArrayLists even arrays:

ArrayList fileList = new ArrayList();

BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\Serene\\Documents\\Major Project\\Alignment Algorithms\\Testing2.txt")); //reading files in specified directory

 
String line = null;

while ((line = in.readLine()) != null) {
   line = line.trim(); // get rid of trailing spaces: " 1,2,3 " becomes: "1,2,3"
   System.out.println("Line is: "+line); // for debuging

   String [] arr = line.split(","); // now you have an array of {"1","2","3"}

   fileList.add(arr); // the list has all of the arrays
}

// There is a method that converts a list into an array. If the list has values "a", "b", "c" that method will return an array of {"a","b","c"}
// So by using that method you will get an array of arrays, which is a 2D array in java:

String [][] finalArr = (String [][])fileList.toArray();
// each row of the array will have each line. And each column of each row will have the columns of the file

If the method toArray is complicated, once you have the fileList you can do it manually:

int rows = fileList.size(); // lines of the file
String [][] Arr2D = new String[rows][];
for (int i=0;i<rows;i++) {
  String [] arr = (String [])fileList.get(i);
  Arr2D[i] = arr;
}

Remember 2D arrays in java are an array of arrays. So each element of a 2D array is an array:
String [][] ARR -> 2D array:
ARR is an 1D array
ARR[j] is the value of the jth element of the ith array, or the ith row, jth col.

Or:

int rows = fileList.size(); // lines of the file
String [][] Arr2D = new String[rows][];

for (int i=0;i<rows;i++) {
  String [] arr = (String [])fileList.get(i);
  
  Arr2D[i] = new String[arr.length];

  for (int j=0;j<arr.length;j++) {
     Arr2D[i][j] = arr[j];
  }
}

Thank you so much. I will read and digest it and try it out and see if it works.

Oh what about parsing it? You did not include the parsing into double part.

Oh what about parsing it? You did not include the parsing into double part.

It's not that difficult to add this:
Double.parseDouble in the code, wherever you want it to happen.

You can do it after you got the 2D array of before. You can parse the input, create an 1D double array and add that to the list.
With that code given it's up to you to add the parsing. I am not going to do the whole thing, you need to put some of work. If you want double just create a double array parse the values inside it and then continue using those arrays. Do some thinking on your own.

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

public class Testing3
{

	//static double[][] myDouble;
    //static int a, b;
    //static double d;
	//static String[] temp;

	static ArrayList myDouble = new ArrayList();
	static String[] temp;
	static String [][] finalTemp;
	static int rows;

	public static void main(String args[])
	{

		try
        {
            BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\Serene\\Documents\\Major Project\\Alignment Algorithms\\Testing2.txt"));	//reading files in specified directory

            String str = null;
            while ((str = in.readLine()) != null)	//file reading
            {
				str = str.trim();
				temp = str.split(",");
				myDouble.add(temp);
				
				finalTemp = (String [][])myDouble.toArray();
				

				/*rows = myDouble.size();
				finalTemp = new String[rows][];

				for (int i=0;i<rows;i++)
				{
  					String[] arr = (String[])myDouble.get(i);
  					finalTemp[i] = arr;
				}*/



            }
			in.close();


        }catch( IOException ioException ) {}

	}

}

This is what I have now, but I'm having error at the line,
finalTemp = (String [][])myDouble.toArray();

I will have error saying ClassCastException.

You need to convert the list to an array after you have read the file. What is it doing inside the while. First read the file and put it into the list. Then outside the while after reading the entire file, convert it into a 2D array. Also if the (String [][]) doesn't seem to work use the second approach:

while ((str = in.readLine()) != null)	//file reading
            {
				str = str.trim();
				temp = str.split(",");
				myDouble.add(temp);
            }

// Now that you have the myDouble convert into an array:
int rows = myDouble.size(); // number of lines of the file.
finalTemp = new String[rows][];

for (int i=0;i<rows;i++) {
 String[] arr = (String[])myDouble.get(i); // each element of the list is an array

 finalTemp[i] = arr; // the ith element of the finalTemp 2D array is an 1D array
}

Remember the finalTemp is a 2D array, the finalTemp is an 1D array, the finalTemp[j] is a String.
Now print the finalTemp array using for loops and see what values it has. Compare them with the data of the file.
Don't continue until you have successfully finished with the file reading. Once you are ok, just for loop the 2D array, convert each of its elements into a number and put that number into an new double array that has the same size as the finalTemp.

hmm, I dont have that error, finalTemp = (String [][])myDouble.toArray(); works fine...

hmm, I dont have that error, finalTemp = (String [][])myDouble.toArray(); works fine...

Maybe it has something to do java version. After all the toArray is supposed to return a 1D array. Even if each of its elements would be another array.

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

public class Testing3
{
        static ArrayList myDouble = new ArrayList();
	static String[] temp;
	static String [][] finalTemp;
	static int rows;

	public static void main(String args[])
	{

		try
        {
            BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\Serene\\Documents\\Major Project\\Alignment Algorithms\\Testing2.txt"));	//reading files in specified directory

            String str = null;
            while ((str = in.readLine()) != null)	//file reading
            {
				str = str.trim();
				temp = str.split(",");
				myDouble.add(temp);
            }

            finalTemp = (String [][])myDouble.toArray();

            for(int i=0; i<rows; i++)
            {
            	for(int j=0; j<i; j++)
            	{
            		System.out.println(finalTemp[i][j]);
            	}
            }
            in.close();


        }catch( IOException ioException ) {}

	}

}

This is what I have so far. I can't seem to print finalTemp. Is the for loop correct?
I also have this error:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
at Testing3.main(Testing3.java:26)

i wonder if using the (confusingly named) myDouble array with generics would help the compiler with that error:

myDouble<String []> = new ArrayList<String []>();

Oh, and I just realised I didnt actually run the code and ClassCastException is a run time exception, so I'm not sure if it did work.

If generics doesnt work you will have to make a new method as javaAddict suggested and make an array out of it yourself, pretty easy with for loops.

??? No I have more errors. ):

Forget about the (String [][]) it seems that it doesn't work. Try to do it manually like I suggested:

int rows = myDouble.size(); // number of lines of the file.
finalTemp = new String[rows][];

for (int i=0;i<rows;i++) {
  String[] arr = (String[])myDouble.get(i); // each element of the list is an array
  finalTemp[i] = arr; // the ith element of the finalTemp 2D array is an 1D array
}

By the way I just noticed that you loop the array the wrong way:

for(int i=0; i<rows; i++) {
  for(int j=0; j<i; j++) {
   System.out.println(finalTemp[i][j]);
  }
}

You have at the inner loop: j<i Why? Why do you set the upper limit to be i? It should be the length of the array you are trying to read. With the way you have it, the first loop will not print anything since i would be 0. The next loop will print only one element. You need to put the length of the array. At the outer loop you put the length of finalTemp but in the inner loop the array you are looping is: finalTemp:

// rows is in fact finalTemp.length
for(int i=0; i<rows; i++) {
  for(int j=0; j<finalTemp[i].length; j++) {
   System.out.println(finalTemp[i][j]);
  }
}

finalTemp is also an array and you want to print its elements: finalTemp[j] . So its length would be: finalTemp.length

I assume that since the thread is marked as solved you have corrected that error on your own. But in case you didn't I posted

Hi there. Yeah thank you so much!!! It's solved! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.