I encounter a NullPointerException on clickCell[r][c] = false; and on new LifeGUI(new LifeModel(x, y, s); and can't fix it. Please explain why this problem occurs and how I may fix it.
Code:
public LifeModel(int rows, int cols, int cellSize) {
row = rows;
col = cols;
cSize = cellSize;
for (int r = 0; r < row; r++) {
for ( int c = 0; c < col; c++) {
clickCell[r][c] = false;
}
}
}
public static void main(int x, int y, int s) {
new LifeGUI(new LifeModel(x, y, s));
}
You haven't shown where the clickcell array was declared, but likely you have declared it but not initialized it. You may have
boolean[][] clickcell;
but need:
boolean[][] clickcell = new boolean[rows][cols];
where rows and cols represent the size of the array you need.
You have to create the array object
boolean [][] clickCell = new boolean[rows][cols];
Add this command before the for loop.
More info here
If clickCell is declared somewhere else, the command should be:
clickCell = new boolean[rows][cols];
Or as GriffeyDog suggests, add the new boolean[rows][cols] at the place where you declare the array, depending on the logic of your program.
Related
I am trying to make my Face class immutable such that my Face object will not change once it has been initialized. This is what I have so far:
public class Face{
protected final int[][] grid;
protected Face half;
public Face(int[][] grid){
this.grid = grid;
}
public Face rotateRight(){
int rows = 3;
int cols = 3;
int[][] transposedArray = new int[3][3];
for (int i = 0; i<rows; i++){
for (int j = 0; j<cols; j++){
transposedArray[i][j]=grid[rows-j-1][i];
}
}
return new Face(transposedArray);
}
public Face rotateLeft(){
int rows = 3;
int cols = 3;
int[][] transposedArray = new int[3][3];
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
transposedArray[2-j][i] = grid[i][j];
}
}
return new Face(transposedArray);
}
public Face rotateHalf(){
half = this.rotateRight();
half = half.rotateRight();
return half;
}
public int[][] getGrid(){
return (this.grid).clone();
}
public String toString(){
String str = "";
for (int i = 0; i<3;i++){
for (int j = 0; j<3; j++){
str += String.format("%02d",grid[i][j]);
}
}
String str1 = str.substring(0,6);
String str2 = str.substring(6,12);
String str3 = str.substring(12,18);
return str1+"\n"+str2+"\n"+str3;
}
}
However, when I try to run the following:
int[][] g = f.getGrid();
g[1][1] = 9;
I expect f to remain as
010203
040507
070809
but I end up getting
010203
040906
070809
instead. Is my Face object not made immutable even though I have already declared the class as final?
You need to make a defensive copy of the input grid in the constructor.
Also, the fields should be private as well, and the class should be final too, although I suspect those last two points are not the cause of your problem.
Not tested:
public Face(int[][] grid){
int temp[][] = new int[ grid.length ][];
for( int i = 0; i < temp.length; i++ )
temp[i] = Arrays.copyOf( grid[i], grid[i].length );
this.grid = temp;
}
Your problem could be that your constructor doesn't clone the incoming array. So maybe the code that creates the Face class instance later manipulates the array it passed to the new Face object!
Unfortunately, there is no way to create truly immutable arrays in the Java. Declaring an array as final only prevents you from changing the array as a whole, it is still possible to change individual rows, columns, slots in that array.
If you want immutable collections, you need to turn actual Collection classes and then use the methods within the Collections class to create unmodifiable views over them.
Be careful when using clone.
On arrays, it does a shallow copy. The following snippet explains it better:
int[] c0 = new int[]{1, 2, 3};
int[] c1 = new int[]{4, 5, 6};
int[] c2 = new int[]{7, 8, 9};
int[][] grid = new int[][]{c0, c1, c2};
int[][] cloned = grid.clone();
assert cloned[0] == c0;
assert cloned[1] == c1;
assert cloned[2] == c2;
I'm writing a program that creates a maze as a 2d array. I've run into a hiccup, and that is ArrayIndexOutOfBoundsException. It is pointing to maze[0][0] = "S" in the drawMaze method. I'm scratching my head at this, I have no idea why it's throwing an error.
import java.util.Random;
public class LA2_MazeSolver {
private int rows;
private int cols;
private String[][] maze = new String[rows][cols];
LA2_MazeInput mi = new LA2_MazeInput();
public void setNumRows(int numRows) {
this.rows = numRows;
}
public void setNumCols(int numCols) {
this.cols = numCols;
}
public int getNumRows() {
return this.rows;
}
public int getNumCols() {
return this.cols;
}
public void drawMaze() {
Random r = new Random();
maze[0][0] = "S";
maze[rows - 1][cols - 1] = "D";
int limit = ((rows * cols) / 3);
for (int i = r.nextInt(limit) + 1; i < limit; i++) {
maze[r.nextInt(rows) - 1][r.nextInt(cols) - 1] = "#";
}
for (int i = 0; i < maze.length; i++) {
for (int c = 0; c < maze[0].length; c++) {
if (!(maze[i][c].matches("#")) && !(maze[i][c].matches("S")) && !(maze[i][c].matches("D"))) {
maze[i][c] = Integer.toString(r.nextInt(100) + 1);
}
}
}
}
public void printMaze() {
}
/*public boolean isSolvable() {
return solveMazeRecursively(this.rows, this.cols);
}
private boolean solveMazeRecursively(int row, int col) {
}*/
public void printResult() {
}
}
It's simple. You are getting the Array Index Out of Bound exception because you are exceeding the array boundaries.
I've run into a hiccup, and that is ArrayIndexOutOfBoundsException. It is pointing to "maze[0][0] = "S";"
You have declared maze in the following block
private int rows;
private int cols;
private String[][] maze = new String[rows][cols];
Note that you are specifying a size of 'rows' and 'cols' for 'maze'. But these values are 0 and 0 respectively. See that you are not giving a value to rows and cols at the time of initialization. So the default value of int primitives declared as class members is 0.
To fix this problem, initialize rows and cols to a value greater than 0.
In Java, you can't make a definition like private String[][] maze = new String[rows][cols]; outside of the constructor. At that point in the the code, the value for row and col have not been defined and so something like private String[][] maze = new String[rows][cols]; won't have well defined behaviour (row and col may in fact be 0, who knows).
Try instead something like this:
private int row;
private int col;
private String[][] maze;
public LA2_MazeSolver(int row, int col) {
this.row = row;
this.col = col;
maze = new String[row][col]
}
Now when you create a LA2_MazerSolver object, you will dynamically create an array of the correct size to use (for example solver = new LA2_MazeSolver(row, col)).
I want to program a pacmanstyle maze game in Java.
for the maze i am using a property file, in which coordinates are stored (i.e. x=1, y=5 -> wall) as strings in following format: 79,13=0 79,12=0 79,11=0.
I want to create the mazegrid using a 2d array: int [][] maze.
i know how to load in a property file. My problem however is, I have no idea how to first extract the string variables out of the property and second the proper way to fill the array.
public final class Labyrinth {
private int i;
private int j;
private static int [][] maze;
private String p;
private String l;
public void setMaze(int x, int y){
x = this.i;
y = this.j;
}
public static int[][] getMaze(){
return maze;
}
public Labyrinth(int rows, int cols) throws IOException{
try (FileInputStream in = new FileInputStream("level.properties")) {
Properties p1 = new Properties();
p1.load(in);
p = p1.getProperty("Height");
l = p1.getProperty("Width");
cols = parseInt(p);
rows = parseInt(l);
maze = new int[rows][cols];
for (i=0; i < rows; i++){
for(j=0; j < cols; j++){
setMaze(parseInt(p1.getProperty('ValueX,ValueY')),
parseInt(p1.getProperty('ValueX,ValueY')));
}
}
}
}
}
Any helpfull thought will be highly appreciated!
i have no idea how to first extract the string variables out of the .property and second the proper way to fill the array.
What do you mean by extracting string variables? A property file is simply a list of key-value pairs. In your case, the key is x,y and the value is apparently indicating some object in the maze.
You could try reading the keys like this:
for (i = 0; i < rows; i++) {
for(j = 0; j < cols; j++) {
int value = parseInt(p1.getProperty(i + "," + j); // Get the value of (i,j)
maze[i][j] = value; // Assign the value to the maze
}
}
I am relatively new to Java and for a school project I need to print a 2D array. The base for this project is to print it with values null. But I can't put this into a for loop without getting a java.lang.NullPointerException. Can anybody help?
private int ROWS;
private int COLUMNS;
private int WIDTH;
private String[][] sheet;
private String[][] values;
private int precision;
public SpreadSheet(int rows, int cols, int width, int precision) {
this.ROWS = rows;
this.COLUMNS = cols;
/*this.WIDTH = width;
this.precision = precision;*/
}
public void printSheet(){
for (int i = 0; i < sheet.length; i++) {
for (int j = 0; j < sheet[i].length; j++) {
System.out.println(sheet);
}
System.out.println("\n");
}
}
The main :
import java.util.Scanner;
public class DemoSpreadSheet {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
SpreadSheet sh = new SpreadSheet(4, 6, 15, 2);
sh.printSheet();
}
}
Make a small change to the SpreadSheet function:
public SpreadSheet(int rows;int cols;int width;int precision)
{
this.Sheet=new String[rows][cols];
/*creates an array with 4 rows and 6 columns..(assuming this is what you wanted to do)*/
}
There is also an error in your print sheet function:
System.out.println(Sheet); //illogical
/*sheet does not print the content of the array Sheet*/
Change this to:
System.out.println(Sheet[i][j]);
/*this will print null */
you need to initialisé your arrays.
sheet = new String[rows][cols]
This is an exemple you have other errors in you class.
This will do it (including better format):
public void printSheet(){
for (int i = 0; i < sheet.length; i++) {
for (int j = 0; j < sheet[i].length; j++) {
System.out.print(sheet[i][j] + " ");
}
System.out.println();
}
}
However, you have not assigned a length to your sheet. That means, at some point (at the constructor most likely) you have to define:
sheet = new String[rows][cols];
I'm getting the error "Exception in thread "main" java.lang.NullPointerException" when I try to read an array value. Here is the code that I think causes the error.
class Board
{
private static char[][] board;
public Board(int r, int c)
{
setRow(r);
setColumn(c);
char board[][] = new char[row][column];
}
public void getBoard()
{
for (int c = 1;c <= getColumn()-1 ;c++)
{
System.out.print("\t"+c);
}
System.out.print("\n");
for (int r = 1; r <= getRow()-1; r++)
{
System.out.print(r);
for (int c = 1; c <= getColumn(); c++)
{
System.out.print("\t" + board[r][c]); //I think board[r][c] is causing it.
}
System.out.println("");
}
return;
}
}
I can upload the whole file if need be.
Any help would be appreciated, this kept me up last night.
Replace
char board[][] = new char[row][column];
with
board = new char[row][column];
In the first statement, you're assigning a value to a local variable, not to the one of your instance.
You are hiding member variable in the constructor
char board[][] = new char[row][column];
it should be
board= new char[row][column];