I'm currently practicing algorithms and coding for my colleges programming team. The problem is, in High School I was almost purely C/C++, while my college team all work in Java. So, while not wildly different, learning Java is still pretty frustrating to me.

My most recent problem is a Java.lang.NullPointerException on line 26 (it's commented where it breaks). It is reading the file and creating the rectangles[] array properly. The file calls for 9 rectangles, and it creates indexes rectangles[0...8]. But each of the indexes is set to null when I pause the debugger. So Java will make my array, but not populate it? I haven't had this problem when using standard types like int or boolean arrays... any help please? I'm sure it's a pretty novice mistake, it may not even be Java and my tired eyes are missing an obvious typo?

package RectanglesInt;
import java.util.*;
import java.io.*;

public class RectanglesInt {
	
	public class rectangle {
		int xMin, xMax, yMin, yMax, area;
		boolean intersects;
	}

	static rectangle rectangles[];
	
	public static void main(String args[]) throws Exception {
		Scanner in = new Scanner(new FileReader("rectangles.in"));
		int numCases = in.nextInt();	//First line of file is # of test cases	
		
		for (int cases = 0; cases < numCases; cases++) {
			int numRectangles = in.nextInt(); //Next line is number of rectangles in set of input
			rectangles = new rectangle[numRectangles];
			
			int xMax, yMax;
			xMax = yMax = 0;
			
			for (int i = 0; i < numRectangles; i++) {
				rectangles[i].xMin = in.nextInt(); //Crashes right here. rectangles[0] == null
				rectangles[i].yMin = in.nextInt();

//[code left out for brevity]

When you type
rectangles = new rectangle[numRectangles];

You are just creating an array of "rectangle references" and not an array of "rectangle objects".

This is what you have done :

Rectangle a; //the reference a has not being assigned to any object
a.xmin=0;

This is what you can do to solve the problem :

Rectangle a;
a = new Rectangle(); //now, a refers to a rectangle object
a.xmin=0;

Hope you understood ...... initialize a reference with an object before using it otherwise it would give a null pointer exception because no object has been assigned to it.

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.