How to initialize an array to avoid a Null Pointer Exception? - java

I get a nullPointerException in my program when I try to call a boolean array in a method parameter. The boolean array is created as a constant, and then initialized in a separate void method. Can someone explain to me why it can't find the boolean array (or can't find the array values)?
public static void moveTarget(Graphics g) {
if (!targetMovement)
return;
drawTarget(g, BACKGROUND_COLOR);
drawShield(g, BACKGROUND_COLOR);
This line right here is the specific part where the program fails. (nullPointerException)
int f = findTargetMissilePosition(targetMissileActive);
I specify the constants here, but do not initialize.
// Target Missile values
public static Color TARGET_MISSILE_COLOR = TARGET_COLOR;
public static int MAX_MISSILES = 10;
public static double TARGET_MISSILE_SPEED = MISSILE_SPEED;
public static double TARGET_SHOOT_PROBABILITY = .1;
public static double[] targetMissilePositionX;
public static double[] targetMissilePositionY;
public static double[] targetMissileDeltaX;
public static double[] targetMissileDeltaY;
public static boolean[] targetMissileActive;
// main method does initialization and calls startGrame
public static void main(String[] args) {
DrawingPanel panel = new DrawingPanel(PANEL_WIDTH, PANEL_HEIGHT);
Graphics g = panel.getGraphics( );
initialize();
startGame(panel, g);
}
//initialize() is called above which is where the arrays are intialized
// start the main game loop which runs forever
public static void startGame(DrawingPanel panel, Graphics g) {
while(true) {
panel.sleep(SLEEP_TIME);
handleKeys(panel,g);
moveTarget(g);
drawAll(g);
moveMissile(g);
shootTargetMissile(g);
for (int i=0;i<10;i++) {
int f = findTargetMissilePosition(targetMissileActive);
moveTargetMissile(g, f);
}
shieldHitTimer--;
targetHitTimer--;
shooterHitTimer--;
}
}
// above is the first time that line of code appears and does not appear to have an issue.
// reset all parameters to start over
public static void reset(Graphics g) {
g.setColor(BACKGROUND_COLOR);
g.fillRect(0,0,PANEL_WIDTH,PANEL_HEIGHT);
initialize();
}
//Here the arrays are initialized
// initialize parameters for the start of the program
public static void initialize() {
shooterPositionX = SHOOTER_INITIAL_POSITION_X;
gunAngle = 0;
targetPositionX = PANEL_WIDTH/2;
missileActive = false;
hitCount = 0;
shooterHitCount = 0;
hitDisplayString = "Hits: ";
targetDeltaX = 0;
targetHitTimer = 0;
shieldHitTimer = 0;
shooterHitTimer = 0;
boolean [] targetMissileActive = new boolean [9]; // might change??
int [] targetMissilePositionX = new int [9];
int [] targetMissilePositionY = new int [9];
int [] targetMissileDeltaX = new int [9];
int [] targetMissileDeltaY = new int [9];
for (int i=0; i<9; i++) {
targetMissilePositionX[i] = 0;
targetMissilePositionY[i] = 0;
targetMissileDeltaX[i] = 0;
targetMissileDeltaY[i] = 0;
targetMissileActive[i] = false;
}
}
// draw everything in its current position
public static void drawAll(Graphics g) {
g.setColor(Color.BLACK);
g.drawString("Project 3 by Benjamin Koch",10,15);
g.drawString(hitDisplayString,10,30);
int f = findTargetMissilePosition(targetMissileActive);
drawTargetMissile(g, TARGET_MISSILE_COLOR, f);
drawShooter(g,SHOOTER_COLOR);
if (targetHitTimer > 0)
drawTarget(g, SHIELD_HIT_COLOR);
else
drawTarget(g,TARGET_COLOR);
Color shieldColor = BACKGROUND_COLOR; // default: do not draw
if (shieldActive) {
if (shieldHitTimer > 0)
shieldColor = SHIELD_HIT_COLOR;
else
shieldColor = SHIELD_COLOR;
}
drawShield(g, shieldColor);
}
public static int findTargetMissilePosition (boolean[] data) {
for (int i=0;i<MAX_MISSILES;i++) {
if (data[i]==false) {
return i;
}
}
return -1;
}

Inside your initialize() function, you're creating local variables but not initializing the global ones.
targetMissileActive = new boolean [9];
targetMissilePositionX = new int [9];
targetMissilePositionY = new int [9];
targetMissileDeltaX = new int [9];
targetMissileDeltaY = new int [9];
for (int i=0; i<9; i++) {
targetMissilePositionX[i] = 0;
targetMissilePositionY[i] = 0;
targetMissileDeltaX[i] = 0;
targetMissileDeltaY[i] = 0;
targetMissileActive[i] = false;
}
This will reference the variables to the global one.

Related

java.lang.NullPointerException appearing for no reason [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have made a program inside of which, there is a specific method that makes sure that all of the objects in an array that point to null point to a blank space. For some reason, whenever I run the code, it gives me a java.lang.NullPointerException.
I understand what a NullPointerException is, which is why I added the if statement, so that it wouldn't give the error, but it still does
Code:
public class TextGraphics {
public static void main(String[] args) {
displaySize size = new displaySize(5,5);
displaySize.output(5,3,size,"H");
displaySize.run(size);
}
}
class displaySize {
public static int indent;
public static int sizeX = 0;
public static int sizeY = 0;
public displaySize() {
}
public displaySize(int screenX, int screenY) {
sizeX = screenX;
sizeY = screenY;
indent = sizeX;
}
public static void output(int x, int y, displaySize size, String print) {
rarray(size)[x + y * size.sizeX] = print;
}
public static String[] rarray(displaySize size) {
String [] display;
return display = new String[sizeX * sizeY];
}
public static void run(displaySize size) {
int next = 0;
for (int i = 0; i < sizeY; i++) {
for (int b = 0; b < indent; b++) {
next++;
if(rarray(size)[next].equals(null) )
{
System.out.print( rarray(size)[next] + " ");
rarray(size)[next] = " ";
}
System.out.print( rarray(size)[next] + " ");
}
System.out.println("/n");
}
}
}
first problem used .equals(null) instead of == null
second problem your code throws a arrayoutofindex because your next++ was in the wrong for loop
finally your new line character was wrong its \n not /n
corrected code
public class TextGraphics {
public static void main(String[] args) {
displaySize size = new displaySize(5,5);
displaySize.output(5,3,size,"H");
displaySize.run(size);
}
}
class displaySize {
public static int indent;
public static int sizeX = 0;
public static int sizeY = 0;
public displaySize() {
}
public displaySize(int screenX, int screenY) {
sizeX = screenX;
sizeY = screenY;
indent = sizeX;
}
public static void output(int x, int y, displaySize size, String print) {
rarray(size)[x + y * size.sizeX] = print;
}
public static String[] rarray(displaySize size) {
String [] display;
return display = new String[sizeX * sizeY];
}
public static void run(displaySize size) {
int next = 0;
for (int i = 0; i < sizeY; i++) {
next++;
for (int b = 0; b < indent; b++) {
if(rarray(size)[next]==(null) )
{
rarray(size)[next] = " ";
System.out.print( rarray(size)[next] + " ");
}
System.out.print( rarray(size)[next] + " ");
}
System.out.println("\n");
}
}
}

Error when Calling a Java Method

I am new to Java and am having an issue calling a method. I was hoping someone might be able to help me figure out what is going on.
The code I have is as follows:
public class QuickFindUF
{
private int[] id;
public QuickFindUF(int N)
{
id = new int[N];
for (int i = 0; i < N; i++)
id[i] = i;
}
public boolean connected(int p, int q)
{ return id[p] == id[q]; }
public void union(int p, int q)
{
int pid = id[p];
int qid = id[q];
for (int i = 0; i < id.length; i++)
if (id[i] == pid) id[i] = qid;
}
}
I took a look on Stack and figured the way to call my method would be using the following code: QuickFindUF x = new QuickFindUF(10);
When I run this I get an error that says
QuickFindUF.java:27: error: class, interface, or enum expected
QuickFindUF x = new QuickFindUF(10);
^
1 error
If someone could point me in the right direction I would really appreciate it. Thanks.
If the code you posted is your complete code, it appears you need a main method.
public class QuickFindUF
{
//
// add this so you can run code when your program executes
//
public static void main(String[] args)
{
QuickFindUF x = new QuickFindUF(10);
//
// call your methods on x here
// e.g.
// boolean connected = x.connected(2, 3);
//
}
private int[] id;
public QuickFindUF(int N)
{
id = new int[N];
for (int i = 0; i < N; i++)
id[i] = i;
}
public boolean connected(int p, int q)
{ return id[p] == id[q]; }
public void union(int p, int q)
{
int pid = id[p];
int qid = id[q];
for (int i = 0; i < id.length; i++)
if (id[i] == pid) id[i] = qid;
}
}
Your main method might be outside the class , You need to declare main method inside the class like this way :
public static void main(String []args){
QuickFindUF x = new QuickFindUF(10);
}

Random array of 1's and 0's using methods

I am trying to create a random sized array of 1's and 0's. I can get the program to run and compile if I remove the random aspect of the of it and enter the size of the array manually. For some reason when I bring in the random utility I can not get the program to compile.
mport java.util.Random;
public class Project1a {
int[][] sample={{0,0,1,1,1},
{1,1,0,1,1},
{1,1,1,0,1},
{0,1,0,1,1}};
int box[][];
Random randomNumbers = new Random();
int m = randomNumbers.nextInt(100);
int n = randomNumbers.nextInt(100);
int results[][] = new int [m][n];
int goodData = 1;
public static void main(String[] args){
analyzeTable();
printTable(results);
}
public void analyzeTable() {
int row=0;
while (row < sample.length) {
analyzeRow(row);
row++;
}
}
public void analyzeRow(int row) {
int xCol = 0;
int rCount = 0;
while (xCol < sample[row].length) {
rCount = analyzeCell(row,xCol);
results[row][xCol] = rCount;
xCol++;
}
}
int analyzeCell(int row, int col) {
int xCol = col;
int runCount = 0;
int rowLen = sample[row].length;
int hereData = sample[row][xCol];
while (hereData == goodData && xCol < rowLen) {
runCount++;
xCol++;
if (xCol < rowLen) { hereData = sample[row][xCol];}
}
return runCount;
}
public void printTable(int[][] aTable ) {
for (int[] row : aTable) {
printRow(row);
System.out.println();
}
}
public void printRow(int[] aRow) {
for (int cell : aRow) {
System.out.printf("%d ", cell);
}
}
}
Your class name conflicts with java.util.Random. Renaming your class is the easiest fix here.
the problem is you are declaring your instance variable in a block which makes it in-accessible in methods
check this : remove curly braces { } from here and the way you are accessing your results and goodData you need to declare them static
{ // remove this
Random randomNumbers = new Random();
int m = randomNumbers.nextInt(100);
int n = randomNumbers.nextInt(100);
static int results = new int [m][n];
static int goodData = 1;
} // remove this

Client and Object Class outputting values

I have an object and client class created which prints coordinates in order of their distance from the origin. The client class asks the user how many dimensions they want the array to have (x,y or x,y,z) how many points they want generated, and a range from which each coordinate will run from (ex. -x to x, -y to y etc.). When I run the program it prints out the correct number of points, but there is always one extra element in the array (etc. when user enters dimension of array as '4', it always prints out one extra element -> [4, 5, 9, 6, 1]). Why is this happening?
Client Class
import java.io.*;
public class MA {
public MA() { }
public static void main(String args[]) throws IOException {
String myString = "arrayNumPoints.txt";
int numpoints = 0;
int dimension = 0;
double lengthscale = 0;
double [][] points = new double[numpoints][dimension + 1];
BufferedReader myInput = new BufferedReader(new InputStreamReader(System.in));
MB pointsB = new MB();
System.out.println("Enter number of points:");
String numpointsA = myInput.readLine();
numpoints = Integer.parseInt(numpointsA);
pointsB.setnumpoints(numpoints);
System.out.println("Enter the dimension:");
String dimensionA = myInput.readLine();
dimension = Integer.parseInt(dimensionA);
pointsB.setdim(dimension);
System.out.println("Enter length(range):");
String lengthscaleA = myInput.readLine();
lengthscale = Double.parseDouble(lengthscaleA);
pointsB.setlengthscale(lengthscale);
pointsB = new MB(numpoints, lengthscale, dimension, points);
pointsB.fillarray(pointsB.getarray(), pointsB.getlengthscale(), pointsB.getdim(), pointsB.getnumpoints());
pointsB.caldistance(pointsB.getarray(), pointsB.getnumpoints(), pointsB.getdim());
pointsB.sort(pointsB.getarray(), 0, pointsB.getnumpoints()-1, pointsB.getdim());
pointsB.writefile(pointsB.getarray(), pointsB.getnumpoints(), myString);
pointsB.readfile(myString);
}
}
Object Class
import java.io.*;
import java.util.Arrays;
public class MB {
//variables and arrays are declared
private double lengthscale;
private int numpoints;
private int dimension;
private double [][] points;
//constructor
public MB() { }
//constructor
public MB(double [][] points) {
numpoints = 0;
lengthscale = 0;
dimension = 0;
points = new double[numpoints][dimension + 1];
}
//constructor
public MB(int mynumpoints, double mylengthscale, int mydimension, double [][] mypoints) {
numpoints = mynumpoints;
lengthscale = mylengthscale;
dimension = mydimension;
points = new double[numpoints][dimension + 1];
}
//numpoints getter
public int getnumpoints()
{
return numpoints;
}
//numpoints setter
public void setnumpoints(int mynumpoints) {
numpoints = mynumpoints;
}
//lengthscale getter
public double getlengthscale() {
return lengthscale;
}
//lengthscale setter
public void setlengthscale(double mylengthscale) {
lengthscale = mylengthscale;
}
//dimension getter
public int getdim() {
return dimension;
}
//dimension setter
public void setdim(int mydimension) {
dimension = mydimension;
}
//array getter
public double[][] getarray() {
return points;
}
//array setter
public void setarray(double [][]mypoints, int numpoints, int dimension) {
points[numpoints][dimension] = mypoints[numpoints][dimension];
}
//fill array method
public void fillarray(double [][]mypoints, double mylengthscale, int mydimension, int mynumpoints) throws IOException {
for(int x = 0; x < mynumpoints; x++)
{
for(int y = 0; y < mydimension; y++) {
//fills array with random points within the specified range
mypoints[x][y] = (dimension * Math.random() - 1) * mylengthscale;
}//end for
}//end for
}
//writefile method
public void writefile(double [][]mypoints, int mynumpoints, String myString) throws IOException {
//writes to myString
PrintWriter fileOut = new PrintWriter(new FileWriter(myString));
//for loop runs for length of mylengthscale
for(int m = 0; m < mynumpoints; m++) {
//prints points to file
fileOut.println(Arrays.toString(mypoints[m]));
}
//close file
fileOut.close();
//end for
}
//readfile metod
public void readfile(String myString) throws IOException
{
String filePath = myString;
//reads data from mString
BufferedReader in = new BufferedReader(new FileReader(new File(myString)));
String line = null;
while(( (line = in.readLine()) != null))
System.out.println(line);
in.close();
}
//caldistance method
public void caldistance(double [][]mypoints, int mynumpoints, int mydimension) {
//for loop; calculates distance for specified number of points
for(int i = 0; i < mynumpoints; i++) {
for(int k = 0; k < mydimension; k++) {
mypoints[i][mydimension] = mypoints[i][k] * mypoints[i][k];
}//end for loop
mypoints[i][mydimension] = Math.sqrt(mypoints[i][mydimension]);
}//end for loop
}
//sort method
public double[][] sort(double[][] mynewpoints, int down, int top, int mydimension) {
System.arraycopy(mynewpoints, 0, mynewpoints, 0, mynewpoints.length);
//variables are declared
int d = down;
int u = top;
//determines pivot point
double [] pivot = mynewpoints[(down + top)/2];
//sorts the values of the array, comparing it to the pivot
do {
while (mynewpoints[d][mydimension] < pivot[mydimension]) {
d++;
}
while (mynewpoints[u][mydimension] > pivot[mydimension]) {
u--;
}
if (d <= u) {
double[] temporary = new double[mynewpoints[d].length];
//compres values in array and switches them
for (int y = 0; y < mynewpoints[d].length; y++) {
temporary[y] = mynewpoints[d][y];
mynewpoints[d][y] = mynewpoints[u][y];
mynewpoints[u][y] = temporary[y];
}
d++;
u--;
}
} while (d <= u);
if (down < u) {
mynewpoints = sort(mynewpoints, mydimension, down, u);
}
if (d < top) {
mynewpoints = sort(mynewpoints, mydimension, d, top);
}
return mynewpoints;
}
}
You should be more specific (show us the code fragments, which you use and which go wrong).
However do you realize, that in your MB constructor :
//constructor
public MB(double [][] points) {
numpoints = 0;
lengthscale = 0;
dimension = 0;
points = new double[numpoints][dimension + 1];
}
The last line is not doing anything? You have to write it like this :
this.points = new double[numpoints][dimension + 1];
Because you have two variables points, one is class variable, second is passed as parameter. If this happens, without using this the non-class variable is chosen.
Probably because you're adding 1 to the dimension given by the user:
points = new double[numpoints][dimension + 1];
This results in the array having one more column than value of dimension.

Java parameter passing int[][]

I am trying to write a simple DCT algorithm in java. I want my findDCT method to have as a parameter an integer array like this:
public class DCT {
private Random generator = new Random();
private static final int N = 8;
private int[][] f = new int[N][N];
private double[] c = new double[N];
public DCT() {
this.initializeCoefficients();
}
private void initializeCoefficients() {
int value;
// temporary - generation of random numbers between 0 and 255
for (int x=0;x<8;x++) {
for (int y=0;y<8;y++) {
value = generator.nextInt(255);
f[x][y] = value;
System.out.println("Storing: "+value+" in: f["+x+"]["+y+"]");
}
}
for (int i=1;i<N;i++) {
c[i]=1/Math.sqrt(2.0);
System.out.println("Storing: "+c[i]+" in: c["+i+"]");
}
c[0]=1;
}
public double[][] applyDCT() {
double[][] F = new double[N][N];
for (int u=0;u<N;u++) {
for (int v=0;v<N;v++) {
double somme = 0.0;
for (int i=0;i<N;i++) {
for (int j=0;j<N;j++) {
somme+=Math.cos(((2*i+1)/(2.0*N))*u*Math.PI)*Math.cos(((2*j+1)/(2.0*N))*v*Math.PI)*f[i][j];
}
}
somme*=(c[u]*c[v])/4;
F[u][v]=somme;
}
}
return F;
}
}
Now, how would I declare this method and to be able to pass 'int[][] f' as a parameter instead of using f[][] declared as a private variable and initialized in the constructor of the current class?
How about extracting the initializeCoefficients and changing the constructor from
public DCT() {
this.initializeCoefficients();
}
to
public DCT(int[][] f) {
this.f = f;
}
You could then use the class like
double[][] dctApplied = new DCT(yourTwoDimF).applyDCT();
Also, I wouldn't use N the way you do. I would look at the dimensions of f itself when applying the DCT.
That is, I would change
double[][] F = new double[N][N];
for (int u=0;u<N;u++) {
for (int v=0;v<N;v++) {
// ...
to something like
double[][] F = new double[f.length][];
for (int u = 0; u < f.length; u++) {
F[u] = new double[f[u].length];
for (int v=0;v<N;v++) {
// ...

Categories

Resources