Nullpointer Exception in function with 2d array as argument - java

I excepted that my functions in Level.java class allow me to make 2D array copy at any time in my program then change size of level array and fill it with values of copy and at last display it.
When I try to run my program it shows NullPointerException at line 24 in Level.java (a part which replaces the values).
Game.java Class
package main;
public class Game {
public static void main(String[] args) {
Level lvl = new Level();
char[][] exampleLevelTemplate = new char[][] {
{'#','#','#'},
{'#','#','#'},
{'#','#','#'}
};
lvl.setLevelSize(3,3);
lvl.setLevelLayout(exampleLevelTemplate);
lvl.displayLevel();
}
}
Level.java Class
package main;
public class Level {
private int levelWidth;
private int levelHight;
private char[][]level;
public void setLevelSize(int Width,int Height)
{
levelWidth = Width;
levelHight = Height;
char[][]level = new char[levelWidth][levelHight];
}
public void setLevelLayout(char[][]levelTemplate)
{
int a;
int b;
for(a=0; a < levelWidth; a++)
{
for(b=0; b<levelHight; b++)
{
level[a][b] = levelTemplate[a][b]; //Error happens here
}
}
}
public void displayLevel()
{
int a;
int b;
for(a=0; a < levelWidth; a++)
{
for(b=0; b<levelHight; b++)
{
System.out.println(level[a][b]);
}
}
}
}

Change your setLevelSize method to this:
public void setLevelSize(int Width,int Height)
{
levelWidth = Width;
levelHight = Height;
level = new char[levelWidth][levelHight];
}
You will see that line:
char[][]level = new char[levelWidth][levelHight];
was changed to:
level = new char[levelWidth][levelHight];
You need to just assign the array Object to array reference variable "level" and not create a local one and initialize it like you did.
You have been assigning value to a null array reference variable and therefore got NullPointerException.

Related

How do I store objects of sub classes in array?

The question is to create objects of both sub classes and store them in an array .
So I create a abstract Super class and made a method area abstract after that I created the two sub classes and implemented that method on the main method I declared array and given the values this is it. I am new here so sorry if I'm asking it in wrong way.
And yes the output should be the area and types of two figure.
package Geometric;
public abstract class GeometricFigure {
int height;
int width;
String type;
int area;
public GeometricFigure(int height, int width) {
//super();
this.height = height;
this.width = width;
}
public abstract int area();
}
package Geometric;
public class Square extends GeometricFigure {
public Square(int height, int width) {
super(height,width);
}
public int area(){
return height * width;
}
}
package Geometric;
public class Triangle extends GeometricFigure {
public Triangle(int height, int width) {
super(height ,width);
}
public int area() {
return (height*width)/2;
}
}
package Geometric;
public class UseGeometric {
public static void main(String args[]) {
GeometricFigure[] usegeometric = { new Square(12, 15), new Triangle(21, 18) };
for (int i = 0; i < usegeometric.length; i++) {
System.out.println(usegeometric[i]);
usegeometric[i].area();
System.out.println();
}
}
}
You already are storing both elements in an array, I think your question is more related to this part:
usegeometric[i].area();
System.out.println();
You get the area of both elements, but you don't assign it to a variable, and you don't do anything with it. Change those lines of code to this:
System.out.println("Area: " + usegeometric[i].area());
EDIT:
Geometric.Square#19dfb72a Geometric.Triangle#17f6480
This is the kind of output you can expect because you didn't overwrite the toString method in your classes.
If you don't, it will take the inherited version of Object, which prints this information
--
In your Square class, add this:
public String toString() {
return "Square - area = " + area();
}
or something similar, depending on what you want to be printed. (And a similar adjustment to your Triangle class).
At this time, you are printing Object's version of toString, since you didn't provide a new one. By overwriting that method, you should get the output you want after turning your loop into:
for (int i = 0; i < usegeometric.length; i++) {
System.out.println(usegeometric[i]);
}
What println actually does, is not print the object itself, but a String representation of the object, which is provided by the toString method.
public class UseGeometric {
public static void main(String[] args) {
// TODO Auto-generated method stub
GeometricFigure[] usegeometric = { new Square(12, 15), new Triangle(21, 18) };
for (int i = 0; i < usegeometric.length; i++) {
System.out.println("Area is: " + usegeometric[i].area());
}
} }

Java Object Array Initialization

I am working on a java project which contains 3 classes and an object array in one of the classes. This project is ultimately supposed to move 4 entity objects around on a board by using the coordinates of the entity objects. These entity objects are stored in an array in the world class. My problem is with the array initialization in the world class. I am not sure how to set each element of the array equal to an object from the entity class and then access that object's coordinates to move it around on the board. The coordinates for the entity objects are initially set at 20x30 in a default constructor. Here is my code:
public class entity {
private int xcoordinate;
private int ycoordinate;
private String name;
private char symbol;
public entity(){
xcoordinate = 20;
ycoordinate = 30;
}
private entity(int newxcoor, int newycoor, String newname, char newsymbol){
xcoordinate = newxcoor;
ycoordinate = newycoor;
name = newname;
symbol = newsymbol;
}
public int getXCoor(){
return xcoordinate;
}
public int getYCoor(){
return ycoordinate;
}
}
public class world {
private entity[] ObArray = new entity[4];
public world(){
world test = new world();
}
public void draw(){
for (int i = 0; i < 4; i++)
{
//int x = ObArray[i].getXLoc();
//int y = ObArray[i].getYLoc();
}
}
}
public class mainclass {
public static void main(String[] args){
world worldob = new world();
//entity a = new entity();
//entity b = new entity();
//entity c = new entity();
//entity d = new entity();
worldob.draw();
}
}
My draw function and main function are not finished. After the array is initialized I will be able to finish the draw method using the entity get functions.
Thanks for your help.
That is one way of doing it. You can also define all of your entities inline like this:
private entity[] ObArray = {
new entity(0,0,"Entity1",'a'),
new entity(10,10,"Entity2",'b'),
new entity(20,20,"Entity3",'c'),
new entity(30,30,"Entity4",'d')
};
A better way may be to do an ArrayList instead of an array:
private List<entity> ObArray = new ArrayList<>();
ObArray.add(new entity(0,0,"Entity1",'a');
ObArray.add(new entity(10,10,"Entity2",'b');
ObArray.add(new entity(20,20,"Entity3",'c');
ObArray.add(new entity(30,30,"Entity4",'d');
To access each element you just need to get the element from the array and either get or set the properties you need:
ObArray[0].getXCoor();
ObArray[0].setXCoor(5);
Your problem is only creating new object of world inside world's constructor which throws stack overflow error, otherwise it is fine:
public world(){ world test = new world(); //REMOVE THIS LINE
}
You simply need to initialise the array. This can be done in the world constructor.
public world()
{
for (int i = 0; i < 4; i++)
{
ObArray[i] = new entity();
}
}
Then you can access the objects in your draw method, as you've shown:
public void draw()
{
for (int i = 0; i < 4; i++)
{
int x = ObArray[i].getXCoor();
int y = ObArray[i].getYCoor();
System.out.println("x" + x);
System.out.println("y" + y);
// Manipulate items in the array
// ObArray[i].setXCoor(10);
}
}
A more complete example, with the move functions added, and the class names capitalised:
public class Entity
{
private int xcoordinate;
private int ycoordinate;
private String name;
private char symbol;
public Entity()
{
xcoordinate = 20;
ycoordinate = 30;
}
private Entity(int newxcoor, int newycoor, String newname, char newsymbol)
{
xcoordinate = newxcoor;
ycoordinate = newycoor;
name = newname;
symbol = newsymbol;
}
public int getXCoor()
{
return xcoordinate;
}
public void setXCoor(int xcoordinate)
{
this.xcoordinate = xcoordinate;
}
public int getYCoor()
{
return ycoordinate;
}
public void setYcoor(int ycoordinate)
{
this.ycoordinate = ycoordinate;
}
public static void main(String[] args)
{
World worldob = new World();
worldob.draw();
worldob.move(0, 15, 30);
worldob.move(1, 45, 0);
worldob.move(2, 23, 27);
worldob.move(3, 72, 80);
worldob.draw();
}
}
class World
{
private final Entity[] ObArray;
public World()
{
this.ObArray = new Entity[4];
for (int i = 0; i < ObArray.length; i++)
{
ObArray[i] = new Entity();
}
}
public void move(int index, int xCoor, int yCoor)
{
if (index >= 0 && index < ObArray.length)
{
Entity e = ObArray[index];
e.setXCoor(xCoor);
e.setYcoor(yCoor);
}
}
public void draw()
{
for (Entity e : ObArray)
{
int x = e.getXCoor();
int y = e.getYCoor();
System.out.println("x" + x);
System.out.println("y" + y);
}
}
}

Accessing an array from a different method

I am trying to access and store information in the array 'qmissed' from the method 'questionsMissed', how would i do that?
Thank you for your help!
public class DriverExam {
public void makeMissedArray(){
int smissedarray = totalIncorrect();
int[] qmissed = new int[smissedarray];
}
public int[] questionsMissed(){
if(totalIncorrect() > 0){
makeMissedArray();
}
int x = 0;
if(totalIncorrect() == 0){
return qmissed;
}
for(int i = 0; i < 20; i++){
if(correct[i] != student[i]){
qmissed[x] = (i+1);
x++;
}
}
return qmissed;
}
}
Looks like you want qmissed to be an instance variable:
public class DriverExam {
int[] qmissed;
public void makeMissedArray(){
int smissedarray = totalIncorrect();
qmissed = new int[smissedarray];
}
...
}
There will be one copy of qmissed for each instance of the DriverExam class, and it can be accessed by any instance method of the class.

Joining method from another class in java

I'm trying to understand Java by trying several things out. I'm using two classes in the same package. One is called Box, the other one is called TestBox. I want to calculate the area of the company box using calculateArea(). This function is in another class TestBox. However the function calculateArea in Box does not respond to the function in TestBox. I'm missing a link between these two classes. This seems like a simple problem, but I have not found the solution yet. Can someone please help me out?
package box;
public class Box {
int length;
int width;
public static void main(String[] args) {
Box company = new Box();
company.length = 3;
company.width = 4;
int area = company.calculateArea();
}
}
package box;
public class TestBox {
int length;
int width;
int calculateArea(){
int area = length * width;
System.out.println("Area= " + area);
return area;
}
}
I think you have to clarify a bit what is your design, I mean what the classes Box and TestBox should do, moreover I advice use to use an IDE such as Eclipse or Intellij Idea helping you with syntax highlight and founding possible errors.
What you are dealing with is the encapsulation, that is
packing of data and functions into a single component.
so it is feasible that the area of the box is calculated by the Box class itself.
About your code, a possible solution could be:
package com.foo;
public class Main {
public static void main(String[] args) {
Box box = new Box(3, 4);
int area = box.calculateArea();
System.out.println("Box area is: " + area);
}
}
class Box {
private int l;
private int w;
Box(int length, int width) {
l = length;
w = width;
}
int calculateArea() {
return l * w;
}
}
Another possible approach could be
package com.foo;
public class Main {
public static void main(String[] args) {
Box box = new Box(3, 4);
TestBox testBox = new TestBox();
int area = testBox.calculateArea(box);
System.out.println("Box area is: " + area);
}
}
class Box {
private int l;
private int w;
Box(int length, int width) {
l = length;
w = width;
}
public int getLength() {
return l;
}
public int getWidth() {
return w;
}
}
class TestBox {
int calculateArea(Box box) {
return box.getLength() * box.getWidth();
}
If you want to have a separate class doing the job, but it is something I do not like, the function computing the area is related to the box and works on box variables, I prefer the first one, but it should be better to have more details in case.
I hope it helps.
As per the below approach, you need to make parameterized constructor where you can pass the value of length and width at the time of creating TestBox object. You also need to create a default constructor for future save in case if later you only want to create default TestBox object like new TestBox();
You can calculate area in you TestBox class and than return the value in the Box class. You don't need to create separate length and width variable in Box class and no need to create a object of Box.
package box;
public class Box {
public static void main(String[] args) {
TestBox company = new TestBox (3,4);
int area = company.calculateArea();
}
}
package box;
public class TestBox {
private int length;
private int width;
TestBox()
{
}
TestBox(int l, int w)
{
this.length = l;
this.width = w;
}
public int getLength() {
return length;
}
public int getWidth() {
return width;
}
int calculateArea(){
int area = length * width;
System.out.println("Area= " + area);
return area;
}
}
public static void main(String[] args) {
TestBox company = new TestBox();
company.length = 3;
company.width = 4;
int area = company.calculateArea();
}
}

why can't I create an instance of MyVector ?

Given the following code , from some reason it won't create an instance of MyVector . What might be the problem ? The problem occurs in the line of Main :
MyVector vec = new MyVector();
However , when I create the an instance of MyVector with the other constructor :
MyVector vec2 = new MyVector(arr);
it compile and the instance is allocated.
class Dot:
public class Dot {
private double dotValue;
public Dot(double dotValue)
{
this.dotValue = dotValue;
}
public double getDotValue()
{
return this.dotValue;
}
public void setDotValue(double newDotValue)
{
this.dotValue = newDotValue;
}
public String toString()
{
return "The Dot's value is :" + this.dotValue;
}
}
class MyVector
public class MyVector {
private Dot[] arrayDots;
MyVector()
{
int k = 2;
this.arrayDots = new Dot[k];
}
public MyVector(int k)
{
this.arrayDots = new Dot[k];
int i = 0;
while (i < k)
arrayDots[i].setDotValue(0);
}
public MyVector(double array[])
{
this.arrayDots = new Dot[array.length];
int i = 0;
while (i < array.length)
{
this.arrayDots[i] = new Dot(array[i]);
i++;
}
}
}
and Main
public class Main {
public static void main(String[] args) {
int k = 10;
double [] arr = {0,1,2,3,4,5};
System.out.println("Enter you K");
MyVector vec = new MyVector(); // that line compile ,but when debugging it crashes , why ?
MyVector vec2 = new MyVector(arr);
}
}
Regards
Ron
I copied your code into my Eclipse IDE and got an "org.eclipse.debug.core.DebugException: com.sun.jdi.ClassNotLoadedException: Type has not been loaded occurred while retrieving component type of array." Exception when I click on the arrayDots variable.
Your code is ok and working. The debugger has a problem because the Dot class is not loaded.
See also: http://www.coderanch.com/t/433238/Testing/ClassNotLoadedException-Eclipse-debugger
You could change your Main as follows (I know this is not very beautiful)
public static void main(String[] args) {
int k = 10;
double [] arr = {0,1,2,3,4,5};
System.out.println("Enter you K");
new Dot(); // the classloader loads the Dot class
MyVector vec = new MyVector(); // that line compile ,but when debugging it crashes , why ?
MyVector vec2 = new MyVector(arr);
}
Your default constructor is not visible. Add public keyword in front of the constructor.

Categories

Resources