954,554 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Exception in thread "main" java.lang.NullPointerException

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?

Sunshineserene
Junior Poster
187 posts since Jul 2010
Reputation Points: 10
Solved Threads: 0
 

Your error occurs in line 29 where you attempt to access mydouble[a][b] 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.

Taywin
Posting Virtuoso
1,727 posts since Apr 2010
Reputation Points: 229
Solved Threads: 239
 

So I have to store my output into arrayList?

Sunshineserene
Junior Poster
187 posts since Jul 2010
Reputation Points: 10
Solved Threads: 0
 

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.

Eric Cute
Posting Whiz in Training
252 posts since Jun 2010
Reputation Points: 55
Solved Threads: 20
 

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

Sunshineserene
Junior Poster
187 posts since Jul 2010
Reputation Points: 10
Solved Threads: 0
 

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);

hanvyj
Posting Whiz in Training
225 posts since Aug 2010
Reputation Points: 17
Solved Threads: 20
 

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

Sunshineserene
Junior Poster
187 posts since Jul 2010
Reputation Points: 10
Solved Threads: 0
 
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)

Sunshineserene
Junior Poster
187 posts since Jul 2010
Reputation Points: 10
Solved Threads: 0
 

"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!)

hanvyj
Posting Whiz in Training
225 posts since Aug 2010
Reputation Points: 17
Solved Threads: 20
 

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.

Eric Cute
Posting Whiz in Training
252 posts since Jun 2010
Reputation Points: 55
Solved Threads: 20
 

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

Sunshineserene
Junior Poster
187 posts since Jul 2010
Reputation Points: 10
Solved Threads: 0
 

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);
hanvyj
Posting Whiz in Training
225 posts since Aug 2010
Reputation Points: 17
Solved Threads: 20
 

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.

Sunshineserene
Junior Poster
187 posts since Jul 2010
Reputation Points: 10
Solved Threads: 0
 

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

hanvyj
Posting Whiz in Training
225 posts since Aug 2010
Reputation Points: 17
Solved Threads: 20
 

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?

Sunshineserene
Junior Poster
187 posts since Jul 2010
Reputation Points: 10
Solved Threads: 0
 

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[i] is an 1D array
ARR[i][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];
  }
}
javaAddict
Nearly a Senior Poster
Team Colleague
3,329 posts since Dec 2007
Reputation Points: 1,014
Solved Threads: 448
 

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

Sunshineserene
Junior Poster
187 posts since Jul 2010
Reputation Points: 10
Solved Threads: 0
 

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

Sunshineserene
Junior Poster
187 posts since Jul 2010
Reputation Points: 10
Solved Threads: 0
 
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.

javaAddict
Nearly a Senior Poster
Team Colleague
3,329 posts since Dec 2007
Reputation Points: 1,014
Solved Threads: 448
 
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.

Sunshineserene
Junior Poster
187 posts since Jul 2010
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: