I have a class ConvexHull which I have to implement for my class. One of the instance variables is an array that holds the object Points.
private Points[] points;
When I go to add a Point to the array in the constructor, I'm given a NullPointerException.
public ConvexHull(int n) throws IllegalArgumentException
{
if (n < 1)
throw new IllegalArgumentException();
else {
Random rand = new Random();
for (int i=0; i<n; i++)
{
int x = rand.nextInt(101)-50;
int y = rand.nextInt(101)-50;
Point p = new Point(x,y);
this.points[i] = p; // NullPointerException is thrown.
this.numPoints = points.length;
}
}
}
Basically, I have no idea why this isn't working and need some help.
Please allocate memory for
private Points[] points;
like this..
public ConvexHull(int n) throws IllegalArgumentException
{
if (n < 1)
throw new IllegalArgumentException();
else {
points=new Points[n]; //this is the line that is added
Random rand = new Random();
for (int i=0; i<n; i++)
{
int x = rand.nextInt(101)-50;
int y = rand.nextInt(101)-50;
Point p = new Point(x,y);
this.points[i] = p; // NullPointerException is thrown.
this.numPoints = points.length;
}
}
}
Because you didn't instantiate the array points. You need something like
private Point[] points = new Point[i];
where i is an integer specifying the array's length. Otherwise points is null and a NullPointerException is thrown.
By the way I don't think there is a class called Points. If you create your own class (in fact you probably don't have to), don't name it using a plural noun.
Yeah the problem with your code is that you have declared the array but you have not initialized the array like
points = new Point[sizeOfYourArray];
and it should fix your problem because there is nothing to start with in the first place so when you initialize it it should be fine.
You didn't new an object for field "pointer" like pointer p = new pointer();, so you will get a NullPointerException.
Related
so, I'm supposed to make a matrix using HashMap<Integer,ArrayList<Number>>, where Number is a class who's instance variables are numerator and denominator.
Class Matrix inherits Class Number, which have methods like fillMatrix(), printMatrix(), addMatrix(Matrix,Matrix) and subMatrix(Matrix,Matrix), problem is in those last two methods, i made them but I'm pretty sure they are completely wrong since i get a NullPointerxception, How do i make such methods?
here is the code.
public class Matrix extends Number implements Calculation
{
public static int rows;
public static int cols;
private ArrayList<Number> myArray;
private ArrayList<Double> myArray2;
private ArrayList<Double> myArray3;
private ArrayList<Double> myArray4;
private HashMap <Integer, ArrayList<Number>> hm;
private HashMap <Integer, ArrayList<Double>> hm2;
public Matrix(int r, int c)
{
hm = new HashMap<>();
hm2 = new HashMap<>();
rows = r;
cols = c;
}
public void fillMatrix()
{
Scanner input = new Scanner(System.in);
myArray = new ArrayList<>();
myArray2 = new ArrayList<>();
System.out.println("Enter the number of rows");
rows = input.nextInt();
System.out.println("Enter the number of columns");
cols = input.nextInt();
Number n = new Number();
for (int i = 0; i < cols;i++)
{
n.setNumerator(i);
n.setDenominator(i+1);
myArray.add(new Number(i,i+1));
double xn = n.getNumerator();
double xd = n.getDenominator();
myArray2.add(xn/xd);
}
for (int i = 0; i < rows; i++)
hm2.put(rows,myArray2);
}
public void printMatrix()
{
for (int i = 0; i < rows; i++)
{hm.put(rows,myArray);
System.out.println(myArray3.toString());
}
}
public Number getItem(int rowNO,int colNO)
{
rows = rowNO - 1;
cols = colNO - 1;
hm.get(rows);
return myArray.get(cols);
}
public void addMatrices(Matrix a, Matrix b)
{
Matrix x1 = new Matrix(rows,cols);
Matrix x2 = new Matrix(rows,cols);
for(int i = 0; i < rows; i++)
{ x1.hm2.get(rows);
x2.hm2.get(rows);
for(int j = 0; j< cols;j++)
{
double a1 = x1.myArray2.get(cols);
double a2 = x2.myArray2.get(cols);
double sum = a1+a2;
myArray3 = new ArrayList<>();
myArray3.add(sum);
}
x1=a;
x2=b;
}
}
public void subMatrices(Matrix a, Matrix b)
{
Matrix x1 = new Matrix(rows,cols);
Matrix x2 = new Matrix(rows,cols);
for(int i = 0; i < rows; i++)
{ x1.hm2.get(rows);
{ x2.hm2.get(rows);
for(int j = 0; j< cols;j++)
{
double a1 = x1.myArray2.get(cols);
double a2 = x2.myArray2.get(cols);
double sub = a1-a2;
myArray4 = new ArrayList<>();
myArray4.add(sub);
}
x1=a;
x2=b;
}
}
}
}
I'm a bit confused here, so I'll point out some things I noticed.
First off it's difficult to understand your code because of the variable names.
Also none of the methods are static, so i don't really understand why you're bringing in two Matrices for the calculation, then setting them equal to the first two you create in the beggining of both methods.
Next, you have two brackets after your for loop in the subtraction method, I'm guessing it was just a typo when pasting in StackOverflow.
The myArray objects you're adding the sum too is not going to be accumulating all the sums because you are creating a new arraylist each time that loop goes through. Create it outside the loop.
The NullPointerException could be anywhere really, it's hard to tell because the code is a bit confusing.
I would recommend using the LWJGL library which has has classes like Matrix4fand methods like Matrix4f.add();which will help you accomplish this.
Try running your program in debug mode so you can understand which statement gives you null pointer exception.
And I've noticed you have your rows and columns as static but you can change change them within constructor. It seems there is a logical mistake there. These two may be the cause of your exception if you didn't ever give initial value of them before.
If your matrixes can have different rows and columns then you definitely shouldn't use static for them.
To actually understand where nullpointerexception is given, you should also write your main code. But like I said, in debug mode, you can also see it yourself.
So, I have this class, that contains another class array, and in the constructor I want to make "n" and "nCod" equal 0.
public class ITable
{
TableRow arr[];
class TableRow
{
long n;
int nCod;
ICode cod;
}
ITable()
{
arr = new TableRow[256];
for(int i=0;i<256;i++)
{
arr[i].n = 0;
arr[i].nCod = 0;
}
}
}
When I run it, Eclipse console tells me:
java.lang.NullPointerException
at jhuffman.def.ITable.<init>(ITable.java:21)
That line is:
arr[i].n = 0;
When you create an array instance with new TableRow[256], each of its elements are initialized to null.
Therefore, each element should be initialized before being accessed :
arr = new TableRow[256];
for(int i=0;i<256;i++)
{
arr[i] = new TableRow (); // add this
arr[i].n = 0;
arr[i].nCod = 0;
}
When you create an object array with no initial values, all the positions in the array will point to null. So, for example, arr = new TableRow[3] would initialize the array as [null, null, null].
Since you did not store any TableRow objects into arr, when you access arr[i], it returns null instead of a concrete object. If you try to access a field in null it will result in a NullPointerException as you have observed.
What you need to do is create the TableRow instances and place them into the array before you try to access them. Something like this:
arr = new TableRow[256];
for (int i = 0; i < arr.length; i++) {
arr[i] = new TableRow();
arr[i].n = 0;
arr[i].nCode = 0;
}
I made a code with that iterates through a single dimensional array of objects of type Point from java.awt.Point. I tried to fill x and y instance variables of each Point in the array with essentially array[iterator].x=iterator.
The code
package onmap;
import java.awt.Point;
public class OnMap {
public static void main(String[] args) {
int width=50;
int height=50;
int area = width * height;
int xn;
int yn;
int i=0;
int t=0;
Point[] map;
map = new Point[area];
map[i].x=0;
System.out.print("first x:" + map[i].x);
for (int n=0; n<area-1;n++){
if (i==width)
{i=0; t++;}
map[n].x=i;
map[n].y=t;
i++;
}
for (int n=0;n<area-1;n++){
xn = map[n].x;
yn = map[n].y;
System.out.print("x: " + xn);
System.out.print(" y: "+yn);
System.out.println(" n: "+n);
}
}
}
I don't understand. Why am I receiving a Null Pointer Exception?
(Netbeans 7.3, Java7)
Because when you initialize
Point[] map;
map = new Point[area];
It contains all null references.It creates an array of Point with each element in the array by default initialized as Point element=null.So, when you try map[0].x it will obviously throw NullPointerException as map[0]==null. Refer to the JLS, which tells us that primitive types in Java are always zero-initialized. References are initialized to null.So in an array of references the default value of each of the element will be null reference.
You need to change your lines like below:
Point[] map;
map = new Point[area];
map[i] = new Point();
map[i].x=0;
Just because your array contains null elements.
You have:
...
map = new Point[area];
map[i].x=0;
...
suppose, area = 2, your array will be:
map[0] = null;
map[1] = null;
You could correct it by doing the following change:
...
map = new Point[area];
// initialize Point array
for (int k=0; k < area; k++) {
map[k] = new Point();
}
// ends initialization
map[i].x = 0;
...
probably because array[iterator]==null or array==null
nothing more.
why dont you just debug?
You are getting NullPointerException because:
You have created array of point objects and to initialize point object you should create point object first by using new keyword. But here you are not creating memory for point objects that is the reason behind this exception.
The following line is absent: map[n] = new Point(); before you make any operations on the array objects, as they are null at that moment.
I'm coming from a C background, and am running into a problem in Java. Currently, I need to initialize an array of variables within an array of objects.
I know in C it would be similar to malloc-ing an array of int within an array of structs like:
typedef struct {
char name;
int* times;
} Route_t
int main() {
Route_t *route = malloc(sizeof(Route_t) * 10);
for (int i = 0; i < 10; i++) {
route[i].times = malloc(sizeof(int) * number_of_times);
}
...
So far, in Java I have
public class scheduleGenerator {
class Route {
char routeName;
int[] departureTimes;
}
public static void main(String[] args) throws IOException {
/* code to find number of route = numRoutes goes here */
Route[] route = new Route[numRoutes];
/* code to find number of times = count goes here */
for (int i = 0; i < numRoutes; i++) {
route[i].departureTimes = new int[count];
...
But its spitting out a NullPointerException. What am I doing wrong, and is there a better way to do this?
When you initialize your array
Route[] route = new Route[numRoutes];
there are numRoutes slots all filled with their default value. For reference data types the default value is null, so when you try to access the Route objects in your second for loop they are all null, you first need to initialize them somehow like this:
public static void main(String[] args) throws IOException {
/* code to find number of route = numRoutes goes here */
Route[] route = new Route[numRoutes];
// Initialization:
for (int i = 0; i < numRoutes; i++) {
route[i] = new Route();
}
/* code to find number of times = count goes here */
for (int i = 0; i < numRoutes; i++) {
// without previous initialization, route[i] is null here
route[i].departureTimes = new int[count];
Route[] route = new Route[numRoutes];
In java when you create an array of Objects, all the slots are declared with there default values as below
Objects = null
primitives
int = 0
boolean = false
these numRoutes slots all filled with their default value i.e. null. When you try to access the Route objects in your loop the array reference is pointing to null, you first need to initialize them somehow like this:
// Initialization:
for (int i = 0; i < numRoutes; i++) {
route[i] = new Route();
route[i].departureTimes = new int[count];
}
for (int i = 0; i < numRoutes; i++) {
route[i] = new Route();
route[i].departureTimes = new int[count];
I'm learning constructors and I understand them for the most part, but I must not understand it enough. I also don't understand this fully. But this code below is supposed to use these constructors:
default constructor, which will be used to fill the matrix with random doubles
constructor which takes a File object, which points to a file
containing a matrix,
constructor which takes a string, which contains the name of the file
constructor which takes a value of type Matrix, and makes a copy of it
constructor which takes a 2D array, and copies its values
And some more, along with a static multiply method. I am supposed to use the commands that are found in main. But I don't quite understand how using a String as the only parameter will do the constructor it's told to, and also the other ones like the default constructor that fills the array with random doubles. I think I should be using this more in my code, but I'm not quite sure.
I mainly just need to be able to set a matrix, fill m1 matrix with random doubles, do it again with m2 matrix, and then use the static multiply method to multiply them, then output the resulting matrix. Thank you.
(Just a heads up, I'm using a 3 by 3 matrix, originally I was supposed to set the size of the matrix to the one found in the text file, but I can also specify the size I want, which I am. And sorry for the messy code. It got all jumbled up while I was trying to figure this stuff out, and I'm afraid of altering it further.)
public class Matrix {
double A[][] = new double[3][3]
// Matrix file name
public Matrix(String name) {
this(new File(name));
}
// Matrix random fill
public Matrix() {
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
this.A[i][j] = (min + Math.random() * (max - min));
}
// Matrix copy
public Matrix(double[][] A) {
private double[][] arrcopy = new double[3][3];
private double[][] array = new double[3][3];
array = A;
for(int i = 0; i < 3; ++i){
for(int j = 0; j < array[i].length; ++j) {
arrcopy[i][j] = array[i][j];
}
}
}
// Set array from text file
public Matrix(File a) {
File f = a;
Scanner inputStreamOne = null;
try{
inputStreamOne = new Scanner(f);
}
catch(FileNotFoundException e){
System.out.printf("Error\n");
}
double arrayOne[][] = new double[3][3];
while(inputStreamOne.hasNextInt()) {
for(int i = 0; i < 3; ++i){
for(int j = 0; j < arrayOne[i].length; ++j){
arrayOne[i][j] = inputStreamOne.nextInt();
}
}
inputStreamOne.close();
}
}
// Gets array in file from string name
public Matrix(String a) {
String inputOne = a;
Scanner inputStreamOne = null;
try{
inputStreamOne = new Scanner(new File(inputOne));
}
catch(FileNotFoundException e){
System.out.printf("Error\n");
}
while(inputStreamOne.hasNextInt()){
for(int i = 0; i < size; ++i){
for(int j = 0; j < arrayOne[i].length; ++j){
arrayOne[i][j] = inputStreamOne.nextInt();
}
}
inputStreamOne.close();
}
}
public static multiply
public static void main(String args[]) {
Matrix m = new Matrix("matrix1.txt");
Matrix m2 = new Matrix("matrix2.txt");
Matrix r = Matrix.multiply(m, m2);
r.output(...);
}
}
Within a constructor or a method this refers to the current object. Within a constructor, if you just use a bare this ( which is to say this without a .method after it ) then it refers to another constructor of the same object that has a different type signature.
Constructors, like any function in Java, can be overloaded. Which is to say, because of Java's type system you can have multiple functions that are of the same name so long as they have different type signatures.
class Foo {
public Foo ( String arg ) {
this(arg, "World");
}
public Foo ( String arg1, String arg2 ) {
// do stuff with arg1 and arg2
}
}
In the above example, one constructor takes a single string and the other takes two. Java won't magically know what to do with the data passed into different constructors. What you have to do is write code in each method so that the resulting object is the same. ( Well technically you don't have to do that, but it's good form ( usually overloaded constructors are for setting default values or for the ease of use of other programmers ))
The this keyword refers to the current object in a constructor or a method, i.e. the object whose constructor or method is being called. Within a constructor, you can also use this to call another constructor in the class.
Refer to http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html for a clear explanation from Java Tutorials.