how to print an empty 2d array without getting a nullpointerexception - java

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];

Related

trouble understanding passing 2d array to methods and displaying

With this program I am supposed to use methods to pass through to obtain user input to fill a 3x4 2d array. Then add the sum of the columns and display the results.
The int[][] grid = fillArray(); has an error that in[][] required. Why am I unable to call my method in the main? This is how the book says to do it along witih countless youtube videos.
public class SumOfColumns {
public static int sumColumn(int[][] m, int columnIndex) {
for (int column = 0; column < 4; column++) {
columnIndex = 0;
for (int row = 0; row < 3; row++) {
columnIndex += m[column][row];
}
}
return columnIndex;
}
public static void main(String[] args) {
***int[][] grid = fillArray();***
}
public static int[][] fillArray(int[][] userInput) {
Scanner input = new Scanner(System.in);
int[][] grid = new int[3][4];
System.out.println("Enter a 3x4 grid of numbers please: ");
for (int row = 0; row < grid.length; row++) {
for (int column = 0; column < grid[row].length; column++) {
grid[row][column] = input.nextInt();
}
}
return grid;
}
}
When you declare your fillArray function you gave it an input of int[][] userInput, but then when you call:
int[][] grid = fillArray();
you don't give fillArray and input of int[][]. If you remove the paramter from the fillArray function that should fix it. It would look like:
public static int[][] fillArray() {
// your code...
}

ArrayIndexOutOfBoundsException for unknown reason

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)).

Java fill int [][] array from property.file

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
}
}

ArrayIndexOutOfBoundsException - I dont understand why I am getting this error

What is wrong with my code? I am trying to pass two arguments(one for random seed and another for the and i get the array our of bounds exception error.. I dont understand what i am doing wrong.. I appreciate any help
import java.util.Random;
public class sparse {
public static int size;
public static int matrix[][] = new int[size][size];
public static int seed;
public static void main(String args[]) {
seed = Integer.parseInt(args[0]);
size = Integer.parseInt(args[1]);
matrix = matrixGen();
}
public static int[][] matrixGen() {
Random r = new Random(seed);
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = r.nextInt(100);
}
}
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print(" " + matrix[i][j]);
}
System.out.println(" ");
}
return matrix;
}
}
You get the error because you allocate the matrix at the time when the size is still zero:
public static int matrix[][] = new int[size][size]; // size is zero here
You need to remove the initialization from the declaration, and move it to the main(), after reading the size from args.
public static void main(String args[]) {
seed = Integer.parseInt(args[0]);
size = Integer.parseInt(args[1]);
matrix = new int[size][size];
matrix = matrixGen();
}
You must initialize the size of the matrix before allocating the space for it:
public static int size = 30; // or whatever value do you want
The static fields seed and size have the default value (0) when you initialize the matrix field.
Thus matrix is a 0x0 array, without space for any element: any access will give such an exception.
To fix, you should set the matrix field in the main function, after arguments' parse.

Help with Two-Dimensional Arrays

First of all, Beginner here.
I'm using this code.
class MDArrays {
public static void main(String[] args) {
int[][] x;
int t=2;
x = new int[2][3];
for(int i=0; i<=1; i++) {
for(int j=0; i<=2; j++) {
x[i][j] = t;
t += 2;
System.out.println(x[i][j]);
}
}
}
}
It compiles perfectly, but when running it, after displaying 3 numbers correctly I'm getting the following error.
Exception in thread "main" java.Lang.ArrayindexOutOfBoundsException : 3 at MDArrays.main(MDArrays.java:13)
Where am I going wrong?
You are incrementing j while checking against i.
for(int j=0; i<=2; j++)
j will keep incrementing which will eventually give you an IndexOutOfBoundsException
for(int j=0; i<=2; j++) {
Is your problem. Try:
for(int j=0; j<=2; j++) {
I would write it like this:
class MDArrays
{
private static final int ROWS;
private static final int COLS;
private static final int START_VALUE;
private static final int INC_VALUE;
static
{
ROWS = 2;
COLS = 3;
START_VALUE = 2;
INC_VALUE = 2;
}
public static void main(String[] args)
{
final int[][] x;
int t;
x = new int[ROWS][COLS];
t = START_VALUE;
for(int row = 0; row < x.length; row++)
{
for(int col = 0; col < x[row].length; col++)
{
x[row][col] = t;
t += INC_VALUE;
System.out.println(x[row][col]);
}
}
}
}
The major difference is that I use the .length member rather than hard coded values. That way if I change it to x = new int[3][2]; then the code magically works and stays within its bounds.
The other big difference is that I use row/col instead of i/j. i/j are fine (and traditional) but I find when dealing with arrays of arrays (Java doesn't actually have multi-dimensional arrays) that it is easier to keep track of things if I use the more meaningful row/col (helps prevent you from doing things like for(int col = 0; row < x.length; col++)... which, incidentally, is the bug you have.

Categories