Why does this code cause a NullPointerException? - java

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.

Related

Rewriting array form Object[] to float[] in Java

I have to get an float[] array from an TockaXY[] array.
Example of TockaXY[] with 4 elements:
[60.039005,86.44917][96.53153,41.086178][19.988914,31.67395][96.84925,41.90731]
but I need an float[]. Tried:
for (int i = 0; i < objectArray.length; i++)
floatArray[i] = (Float)objectArray[i];
But I get error cannot Cast.
Any Ideas?
If i understood it right, you have an array within an array.
if you want to keep it this way than you have to create another array within an array
so;
float floatArray[][]; //declare a 2D array
floatArray = new float[4][2]; //make it's length same as yours
for (int i = 0; i < objectArray.length; i++){
for(int j =0; j<objectArray[i].length; j++){
//parse each value as float, and assign it to your new array
floatArray[i][j] = Float.parseFloat(objectArray[i][j]);
}
}
First of all your given element is not array, its array of array.
You can try this to convert Object[][] to Float[][].
Object[][] objectArray = { { 60.039005, 86.44917 }, { 96.53153, 41.086178 }, { 19.988914, 31.67 },
{ 96.84925, 41.90731 } };
Float[][] floatArray = new Float[objectArray.length][2];
for (int i = 0; i < objectArray.length; i++) {
floatArray[i][0] = ((Double) objectArray[i][0]).floatValue();
floatArray[i][1] = ((Double) objectArray[i][0]).floatValue();
}
System.out.println(floatArray);
Assuming TockaXY is something like
public sclass TockaXY {
private float x;
private float y;
//Constructors, getters, setters etc.
#Override
public String toString() {
return "["+ x + ", " + y + "]";
}
}
and you want a float[] containing the values of x and y from each element of a TockaXY[], the size of the float[] must be 2 * size of TockaXY[].
float [] floatArray = new float[objectArray.length * 2];
for (int i = 0, j=0; i < objectArray.length; i++) {
floatArray[j++] = objectArray[i].getX();
floatArray[j++] = objectArray[i].getY();
}
This: (SomeType) someExpr; is called a cast operation. Unfortunately, there are 3 completely different things that java can do, that all look exactly like this. A real guns and grandmas situation!
Casts can convert things, or can assert generics in types, or can coerce types itself. The latter two, at runtime, do nothing (maybe throw ClassCastException), it's just ways to tell the compiler you know what you are doing; to treat things as different types.
The ONLY one that converts anything is the 'type conversion' mode, and that one only kicks in if both the type in the parentheses and the expression you're applying it on are primitive (auto-unboxing may kick in, but it ends there).
Float is not primitive (float is primitive), so you're not doing a type conversion here, but your question makes it sound like you think you are.
Okay, and.. how do I fix my code?
It looks like TockaXY is a class that looks something like:
class TockaXY {
public float x, y;
}
From your question it is unclear what you want here. Do you want all 8 floats in an 8-sized float array? Do you only want the 'x' elements? Only the 'y' elements?
A TockaXY is not a float (it's a coordinate), so this is not easy, you'd have to program that. For example:
TockaXY[] in = ...;
float[] fs = new float[in * 2];
for (int i = 0; i < in.length; i++) {
fs[i * 2] = in[i].x;
fs[(i * 2) + 1] = in[i].y;
}

Adding object to array and getting NullPointerException

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.

Declaration of Array not accepted

I am creating a class that will play the role of a computer player in a virtual game of sticks. However, when I use the constructor method for this class, I lose the array that I have created, even though I had already declared the array in the state attributes. After 20 minutes, I am completely lost.
I am new to Java, and am trying to learn and get better. Any help would really be appreciated.
Below is the redesigned AI class along with the error that Eclipse keeps on submitting.
public class RedesignedAI {
private int[][] largeArray;
private int AIChoiceStick;
private Random random = new Random();
private int CurrentScore[] = new int[51]; //at max, if 100 sticks are initially chosen, then each player takes at max 50 sticks,
private int h = 0; //^so why not have one more in case
public RedesignedAI(int NumberSticks) //this is a constructor method and creates the arrays that contains a
{
largeArray[][] = new int[NumberSticks][3];
int i = 0;
while(i < NumberSticks)
{
largeArray[i][0] = 1; //ADD THIS
largeArray[i][1] = 1;
largeArray[i][2] = 1;
i++;
}
}
The error: largeArray cannot be resolved to a type.
You initialized the largeArraythe wrong way. Use:
largeArray = new int[NumberSticks][3];
That new allocate a 2D array, so types are coherent both sides of the =.
If you want to allocate chunk by chunk then you should use [] syntax:
largeArray = new int[NumberSticks][]; // array of NumberSticks entries to array of int (not yet determined)
for (int i=0; i<NumberSticks; i++) {
largeArray[i] = new int[3]; // i-th entry of array largeArray is a new array of 3 ints
}
largeArray is a reference to array of reference to array of ints. largeArray[i] is a reference to array of ints. largeArray[i][j]is an int.
Try this
private int[][] largeArray = null;
Initially initialize with null.
then in constructor
largeArray[][] = new int[3][3];
Since value is dynamic and you are changing it anyhow
You have to initialize the array on the top:
private int[][] largeArray = new int[x][y];
An array always has a fixed length. Only a list can variate the length.
Change this:
largeArray[][] = new int[NumberSticks][3];
into this:
largeArray = new int[NumberSticks][3];
Wrong Code:
largeArray[][] = new int[NumberSticks][3];
Instead use:
largeArray = new int[NumberSticks][3];
You don't need the [][] in the largeArray code of the constructor. This will do:
largeArray = new int[NumberSticks][3];
You may find it easier to use ArrayList instead. Maybe something like this:
private List<List<Integer>> largeArray;
...
public RedesignedAI(int NumberSticks) {
largeArray = new ArrayList<>();
int i = 0;
while(i < NumberSticks) {
List<Integer> innerArray = new ArrayList<>();
innerArray.add(1);
innerArray.add(1);
innerArray.add(1);
largeArray.add(innerArray);
i++;
}
}

Understanding constructors and "this"

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.

Returning an Array

I am new to programming and Java and trying to write a program which takes two arrays as input and reports back their sum. I want to do this by creating a class which takes two arrays as constructor inputs and then creating a method that adds them together and a method which prints out this new sum array.
Here is my class:
public class test1 {
int [] a;
int [] b;
int [] final23;
public test1 (int x [], int y [])
{
int [] a = x;
int [] b = y;
}
public int [] sum(int [] x, int[] y)
{
int [] a = x;
int [] b = y;
for (int i = 0; i < Math.min(x.length, y.length); i++)
{
final23 [0]=x[0] + y[0] ;
}
return final23;
}
public void print()
{
for (int i = 0; i < final23.length; i++)
{
System.out.println(final23[0]);
}
}
}
Here is my main class:
public class main1 {
public static void main(String[] args)
{
int l[] = {4,7,2};
int k[] = {4,6,2};
test1 X = new test1(k,l);
X.sum(k,l);
X.print();
}
}
I keep getting an error when I run this through:
Exception in thread "main" java.lang.NullPointerException
at test2.sum(test2.java:17)
at main1.main(main1.java:8)
I guess what I really want is for my sum method to take a test1 object as input. However, I don't know how to do this.
Your variable final23 is never initialized.
In java you have to initialize an array before using it. Either you do it during the declaration (like you did with k and l) or you have to do it later with a new arrayType[arraySize];
Here are the way an array can be declared/initialized.
int[] iArray = {1, 2, 3}; //Declaration, Initialization, set values
int[] iArray; //Declaration
iArray = new int[3]; //Initialization
iArray[0] = 1; //Set value
int[] iArray; //Declaration
iArray = new Array[3]{1, 2, 3}; // Initialization and set values
You can of course for the two last sample put the initialization on the same line that the declaration.
Try this (cleaned) code :
public class test1 {
int[] final23;
public int[] sum(int[] x, int[] y) {
final23 = new int[Math.min(x.length, y.length)];
for (int i = 0; i < final23.length; i++) {
final23[i] = x[i] + y[i];
}
return final23;
}
public void print() {
for (int aFinal23 : final23) {
System.out.println(aFinal23);
}
}
public static void main(String[] args) {
int l[] = {4, 7, 2};
int k[] = {4, 6, 2};
test1 x = new test1();
x.sum(k, l);
x.print();
}
}
Resources :
Oracle.com - Arrays
JLS - Array Initializers
JLS - Array Creation Expressions
I'm going to take a long shot here
public int [] sum(int [] x, int[] y)
{
int [] a = x;
int [] b = y;
for (int i = 0; i < Math.min(x.length, y.length); i++)
{
final23 [0]=x[0] + y[0] ;
}
return final23;
}
As a side comment, I'm guessing that you want to add all of the elements of the vector, not just the first. Change your for-loop body to:
final23 [i]=x[i] + y[i] ;
What's final23? Where is it created?
Try adding this to your constructor
public test1 (int x [], int y [])
{
int [] a = x;
int [] b = y;
this.final23 = new int[Math.min(a.length, b.length)];
}
Now final23 is defined and created, and you can use it in your class.
If you supply test1 with arrays in the ctor, you don't need them in the sum method, just use the ones you have in the class already:
public int [] sum()
{
for (int i = 0; i < Math.min(x.length, y.length); i++)
{
final23 [i]=a[i] + b[i] ;
}
return final23;
}
You also had an error in the sumation, you didn't use the iteration variable, you also need to initialize final23 in the ctor.
You have to initialize final23 array before putting elements in it (on line 17).
**final23 = new int[Math.min(x.length, y.length)];**
for (int i = 0; i < Math.min(x.length, y.length); i++)
{
final23 [0]=x[0] + y[0] ;
}
I see a couple of things to point out here.
public test1 (int x [], int y [])
{
int [] a = x;
int [] b = y;
}
First of all, remember that each test1 object - that is, each instance of your test1 class - has variables named a and b. I'm guessing that in the constructor, you want to take the arrays x and y which were passed as parameters and store them into a and b of the object. To do that, all you have to do is write
a = x;
b = y;
You don't have to write int[] again, not when you just want to access an existing array-type variable. You only write that when you're creating a new array-type variable. In this case, when Java sees that you've written int[] a in the constructor, it thinks you want to create yet another array-type variable named a, separate from the one in the test instance, and that's the one that gets set equal to x. The thing is, that local variable gets lost at the end of the constructor. So you're left with a test1 instance that has variables a and b that still refer to nothing, i.e. they're null.
By the way, since you're going to be using the array final23 later on, you should initialize it. Right now, it refers to null because you never set it to equal anything else. You'll need to create a new array and store it in that variable in order to be able to use it later on. So put this line in your constructor:
final23 = new int[Math.min(a.length, b.length)];
That creates the new array with a length equal to the shorter of the two arrays passed in.
Moving on:
public int [] sum(int [] x, int[] y)
{
int [] a = x;
int [] b = y;
In this bit of code, you have the same issue as in the constructor: you create two new array-type variables a and b that get used instead of the ones in the test1 object. I don't think that's what you meant to do. So I'd say get rid of those last two lines entirely.
There's another problem, though: if you think about it, you still have two arrays stored in the test1 object. Assuming you've fixed your constructor, those are the same two arrays that were passed to the constructor. And now you're getting two new arrays under the names x and y. So you have four arrays total. Which ones did you want to sum up? I'm guessing that you meant to sum the two arrays that were passed to the constructor. In that case, your sum method doesn't need to - and shouldn't - accept more arrays as parameters. Get rid of the parameters x and y, so your sum method just looks like
public int [] sum()
{
Now you have to change the rest of that method to use a and b, starting with the for loop. Change its opening line to this:
for (int i = 0; i < Math.min(a.length, b.length); i++)
{
I notice you were wondering how to get your sum method to take an instance of test1. Well, in a way it actually does. There's a special hidden parameter passed to all methods (except static ones) that contains the object the method was called on - in fact, using your main program as an example you could kind of think of X.sum(k,l); as actually calling test1.sum(X,k,l);, where X is the special hidden parameter. You can access it inside the method using the name this (so you could write this.a instead of just a), but Java is generally smart enough to do that for you.
In the body of the for loop, you have another problem. What you want to do is add up corresponding elements of the arrays, i.e. a[0] + b[0] goes into final23[0], a[1] + b[1] goes into final23[1], and so on. But inside the for loop, you only ever add up element 0 of each array. You need to use the loop index variable i, because that runs through all the values from 0 to the length of the shorter array minus 1.
final23 [i] = a[i] + b[i];
}
return final23;
}
So the first time the loop runs, i will be 0, and you'll set final23[0] = a[0] + b[0]. The next time it runs, i will be 1, and you'll set final23[1] = a[1] + b[1]. And so on.
The same problem occurs in your print method. Each time through the loop, you always print out final23[0], when you really should be printing out final23[i] because i changes each time you go through the loop. Change it to
public void print()
{
for (int i = 0; i < final23.length; i++)
{
System.out.println(final23[i]);
}
}
At this point your program should be working, I think, but there are still some improvements you could make to its design. For one thing, every time you create an object of test1, you know you're immediately going to call sum on it. So why not just put the summing-up code right into the constructor? That way you know that the sum will be computed right when you create the object, and you don't have to call sum explicitly.
Of course, once you do that, you'll have no way to access the array final23 from your main class - except that if you want to print it, you can call the print method. But what if you want to write a main class that, say, adds up two arrays, and then adds the result to a third array? It'd be nice to have a way to get the result from the test1 instance. So you can add an accessor method, possibly named getFinal23, that just returns the sum array final23.
In practice, this operation of adding two arrays would probably be implemented as a static method. So if you want, you could try starting over, and writing it as a static method. (Remember that a static method is one which doesn't receive a special hidden parameter) Inside the static method, you'd have to create the final23 array, go through the loop to compute the sums, and then return the array you created. You'll need to enclose the static method in a class, of course, but that class doesn't have to have a constructor since you never really use it for anything. It'd look something like this:
public class SumClass { // pun intended ;-)
public static int[] sum(int[] x, int[] y) {
// you fill in this part
}
}

Categories