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

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

Related

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

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

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

How would I make a board using 3d generic array

How would I make a board using the 3d generic array that contains col, row, and the stack (contains 4, 3, 2, 1).
This is what I declared:
private int row, col, stack;
int[][][] array3Dboard = new int[row][col][stack];
I just having trouble how to make an board using the multidimensional.
public void initalized(int arg1){
this.playerID = arg1;
this.array3Dboard = new int[4][4][4];
//create a data structure for the current contents of the board and stacks.
}
Thanks.
You need to make sure the class with method initialized() has int[][][] array3Dboard declared as an instance variable.
You also need to write:
int row = 4;
int col = 4;
int stack = 4;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
for (int k = 0; k < stack; k++) {
array3Dboard[i][j][k] = 0; //replace 0 with some numerical value
}
}
}

converting a matrix to string

I am working on writing a matrix, but unfortunately I am stuck with the output.
Instead of showing a matrix, it shows me something like:
actual matrix is
Matrix#512fb063
I need to convert the matrix to a string so that the output will look like this:
expected the matrix:
3 8 72
4 6 60
253 2 1
the code that I've written is this:
import java.util.Random;
final public class Matrix {
private final int size1; // number of rows
private final int size2; // number of columns
private final int[][] data; // M-by-N array
// create size1-by-size2 matrix of 0's
public Matrix(int size1, int size2) {
this.size1 = size1;
this.size2 = size2;
data = new int[size1][size2];
}
// create matrix based on 2d array
public Matrix(int[][] data) {
size1 = data.length;
size2 = data[0].length;
this.data = new int[size1][size2];
for (int i = 0; i < size1; i++)
for (int j = 0; j < size2; j++)
this.data[i][j] = data[i][j];
}
// creates and returns a random size1-by-size1 matrix with values between 0 and 255
public String toString(int size1, int size2) {
Matrix A = new Matrix(size1, size2);
String str = " ";
final int white = 0;
final int black = 255;
for (int i = 0; i < size1; i++)
for (int j = 0; j < size2; j++)
{
A.data[i][j] = white + (int)(Math.random() * ((black ) ));
str = (A.data[i][j]+"\t"+A.data[i][j+1]);
if (i==size1 &&j==size2) str = (A.data[i][j]+"\n");
}
return str;
}
You need to override the public String toString() function. What you are doing now is creating a new function called String toString(int size1, int size2).
Your new function is not called when writing:
System.out.println(myMatrix);
You could either do:
System.out.println(myMatrix.toString(2, 2));
or override the default toString() function.
So the following code should work:
#Override
public String toString() {
Matrix A = new Matrix(size1, size2);
String str = " ";
final int white = 0;
final int black = 255;
for (int i = 0; i < size1; i++)
for (int j = 0; j < size2; j++)
{
A.data[i][j] = white + (int)(Math.random() * ((black ) ));
str = (A.data[i][j]+"\t"+A.data[i][j+1]);
if (i==size1 &&j==size2) str = (A.data[i][j]+"\n");
}
return str;
}
where size1 and size2 are variables in the class.
Your output of actual matrix is Matrix#512fb063 is actually the memory address in Java that your instance of the class Matrix sits in. That's because your program doesn't know how to "print" this class - it doesn't magically know that you want a row/column representation of it.
You've got a number of options:
Your toString(int size1, int size2) is perfect. So when you want to print your matrix, you can go System.out.println(someMatrix.toString(2,2)) will work where someMatrix is an instance of your Matrix class.
If you want it to work properly by you just going System.out.println(someMatrix) then you will need to overwrite your Matrix class' toString() function. You -almost- did that in your toString(int size1, int size2) function but it didn't work because it needs to match exactly the parameters, ie: toString() should take 0 parameters. You will need to write a toString() method which can then call your toString(int size1, int size2)
Somehow you get the hashcode. Maybe you can use http://math.nist.gov/javanumerics/jama/doc/ matrix implementation.
I think this line is not working
str = (A.data[i][j]+"\t"+A.data[i][j+1]);
Don't you get an IndexOutOfBoundexception? Anyway A.data[i][j+1] is always empty within the loop. By the way, Variables in Java are always lower case.
You can simply do :
#Override
public String toString()
{
return toString(size1,size2);
}
Edit : If you want to reflect the real content of your current Matrix :
#Override
public String toString()
{
StringBuilder sbResult = new StringBuilder();
for(int i = 0; i < size1;i++)
{
for(int j = 0; j < size2;j++)
{
sbResult.append(A.data[i][j]);
sbResult.append("\t");
sbResult.append(A.data[i][j+1]);
if(i == size1 && j == size2)
{
sbResult.append("\n");
}
}
}
return sbResult.toString();
}

Java 2d array of objects

I have a cell object with function
public class Cell {
static int X;
static int Y;
static int Val = 0;
static int Player = 0;
public Cell(int a, int b, int p) {
// TODO Auto-generated constructor stub
X = a;
Y = b;
Val = 0;
Player = p;
}
With additional function updateX, updateY, updateVal, updatePlayer and respective get functions. It is called by
Cell[][] grid = new Cell[7][6];
for(int i = 0; i < 7; i++)
for(int j = 0; j < 6; j++)
{
grid[i][j] = new Cell(i, j, 0);
}
System.out.println("wasd");
grid[0][1].updatePlayer(1);
grid[0][1].updateVal(1);
System.out.println("grid[0][1].getval = " + grid[0][1].getVal() + " grid[1][1].getval = " + grid[1][1].getVal());
But the output is
grid[0][1].getval = 1 grid[1][1].getval = 1
and should be
grid[0][1].getval = 1 grid[1][1].getval = 0
What is causing this error?
static int X;
static int Y;
static int Val = 0;
static int Player = 0;
These properties should not be static,following code should be ok:
int X;
int Y;
int Val;//the default int value is zero
int Player;
You made the X, Y, Val and Player variables in the class static. Which means they are shared by all instances of that class, which means their values in all those instances will be exactly the same. I'm pretty sure you wanted to declare those as instance variables instead:
public class Cell {
private int x, y, val, player;
// ...
}
You made Val a static variable, so only one Val variable exists and it is shared by all Cell objects.
change:
static int Val = 0;
to:
int Val = 0;
Similarly if you want individual Cell objects to retain separate instances of your variables (i.e. x,y,Val) you need to take away the static keyword from all of them

Categories