I am new to Java and OOP. I'm having trouble understanding this error that I'm getting:
Exception in thread "main" java.lang.NullPointerException
at main.MyBlock.displayBlock(ProgFunAssignment1.java:66)
at main.ProgFunAssignment1.main(ProgFunAssignment1.java:38)
It also happens with the clearBlock()
method as well. I'm assuming it might be to do with me not understanding how to use the methods I've defined in the myBlock class properly in main? or maybe that I haven't initialized block
properly?
I've looked through some other answers about the same error but can't really seem to find anything that makes enough sense for me to get started on. I've pasted my code below, please help me! Explanations on what this error actually means would be great too, I'd like to actually understand what I've done wrong.
Please ask me for any extra information you might need, sometimes I'm not great at including everything!
package main;
import java.util.Scanner;
import java.lang.*;
public class ProgFunAssignment1 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int maxRows;
int maxColumns;
// initial value selection (TASK D)
do { System.out.println("Please enter the desired row and column lengths of your block");
maxRows = console.nextInt();
maxColumns = console.nextInt();
if ((maxRows < 3 || maxRows > 10) || (maxColumns < 3 || maxColumns > 10)) {
System.out.println("Values invalid, please enter values between 3 and 10");}
} while ((maxRows < 3 || maxRows > 10) || (maxColumns < 3 || maxColumns > 10));
MyBlock block = new MyBlock(maxRows, maxColumns);
//Menu creation (TASK E)
int choice;
int colPosition;
int rowPosition;
do { System.out.println("Please select one of the following options \n 1. Add a House \n 2. Display Block \n 3. Clear Block \n 4. Quit");
choice = console.nextInt();
if (choice == 1) {
System.out.println("Please enter position coordinates of the house:");
rowPosition = console.nextInt();
colPosition = console.nextInt();
// If coordinates not valid, go back to menu
}
else if (choice == 2) {
block.displayBlock();
}
else if (choice == 3) {
block.clearBlock();
}
else if (choice == 4) {
System.exit(0);
}
else {
System.out.println("Choice was not valid, please try again.");
}} while (choice < 0 || choice > 4);
}
}
class MyBlock {
private int[][] block;
boolean vacant;
public MyBlock(int maxRows, int maxColumns) {
int block[][] = new int[maxRows][maxColumns];
vacant = true;
}
public void displayBlock() {
// content of displayBlock() method here
for (int[] x : block)
{
for (int y : x)
{
System.out.print(y + " ");
}
System.out.println();
}
}
public void clearBlock() {
// content of clearBlock() method here
vacant = true;
for (int i = 0; i < block.length; i++) {
for (int j = 0; j< block[i].length; j ++)
block[i][j] = 0;
}
}
public boolean buildHouse(int rowPos, int colPos, int rows, int columns) {
// content of buildHouse() method here
// useful code
if (true)
return true;
else
return false;
}
}