This question already has answers here:
How to clone a multidimensional array in java? [duplicate]
(2 answers)
Closed 8 years ago.
I have an array called maze which in, theory, should get modified only in the updateMaze() method. This is because that is the final result I want to output to the console. The problem is when tempMaze gets modified maze is modified as well. This is not supposed to happen. My first thought was that they are pointing to same reference in memory however I checked and that is false. I do have to mention I used clone() at initialization to make their contents similar, and I am not sure if this could be a issue or not. (Even though I think I understand what clone() does I am not familiar enough to know if it is the problem or not.) My code:
public class ThreadTheMaze {
ArrayList<Cell> result = new ArrayList<Cell>();
private String[][] maze;
private String[][] tempMaze;
private int initRowPosition;
private int initColPosition;
private int amtOfRows;
private int amtOfCols;
public ThreadTheMaze(int initRow, int initCol){
initRowPosition = initRow;
initColPosition = initCol;
result.add(new Cell(initRowPosition, initColPosition));
}
public void loadMaze(){
try{
Scanner in = new Scanner(new File("mazeData.txt"));
while (in.hasNextLine()){
amtOfCols = in.nextLine().length();
amtOfRows++;
}
in.close();
maze = new String[amtOfRows][amtOfCols];
in = new Scanner(new File("mazeData.txt"));
for (int r = 0; r < amtOfRows; r++){
String line = in.nextLine();
for (int c = 0; c < amtOfCols; c++){
maze[r][c] = line.substring(0,1);
line = line.substring(1);
}
}
tempMaze = maze.clone();
}catch (FileNotFoundException e){
System.err.print(e);
}
}
public void printMaze(){
for (int r = 0; r < amtOfRows; r++){
for (int c = 0; c < amtOfCols; c++){
System.out.print(maze[r][c]);
}
System.out.println();
}
}
public void updateMaze(){
for (int i = 0; i < result.size(); i++){
maze[result.get(i).getRow()][result.get(i).getColumn()] = "!";
}
}
/**
#return ArrayList of objects 'Cell' that are the solution to the maze. (Note: if no solution then returns empty ArrayList)
*/
public void solve(Cell cell){
tempMaze[cell.getRow()][cell.getColumn()] = "!";
ArrayList<Cell> neighbors = getNeighbors(cell);
if ((cell.getRow() == 0 || cell.getRow() == tempMaze.length-1) || (cell.getColumn() == 0 || cell.getColumn() == tempMaze[0].length-1)){
return;
}
if ((cell.getColumn() == initColPosition && cell.getRow() == initRowPosition) && neighbors.size() < 1){
return;
}
// If not in init position and has no neighbors then backtrack
if ((cell.getColumn() != initColPosition || cell.getRow() != initRowPosition) && neighbors.size() < 1){
result.remove(result.size()-1);
solve(result.get(result.size()-1));
}else if (neighbors.size() >= 1){ // If has neighbors then choose one and call the method again
result.add(neighbors.get(0));
solve(neighbors.get(0));
}
}
/**
#return ArrayList of objects 'Cell' that are empty and available to move to.
*/
private ArrayList<Cell> getNeighbors(Cell cell){
ArrayList<Cell> neighbors = new ArrayList<Cell>();
int row = cell.getRow();
int column = cell.getColumn();
int[][] moveLocs = {{row-1, column}, {row+1, column}, {row, column+1}, {row, column-1}};
for (int r = 0; r < moveLocs.length; r++){
int tRow = moveLocs[r][0];
int tCol = moveLocs[r][1];
if (isValid(tRow, tCol)){
Cell neighbor = new Cell(tRow, tCol);
neighbors.add(neighbor);
}
}
return neighbors;
}
public boolean isValid(int row, int col){
if(row < 0 || row >= amtOfRows){
return false;
}
if (col < 0 || col >= amtOfCols){
return false;
}
if (!tempMaze[row][col].equals(" ")){
return false;
}
return true;
}
}
The class Cell is a simple class with some simple get and set method.
I know this isn't the most concise way to present you my question, but really I can't spot a place were the problem could exist. Thanks.
clone() is shallow. This means that the following:
tempMaze = maze.clone();
only clones the first level of the 2D array. In other words, you get a new array containing the same String[] references as the original array.
For suggestions on how to fix this, see How do I do a deep copy of a 2d array in Java?
Related
I'm trying to use an array of objects to have barrels fall from the top of the screen to the bottom. (Like that old donkey kong game.) However, I can't seem to find a way to create more instances of the object than whatever the initial length of the array was. Anyone know a way to do this?
Here's the code:
Man Man;
Man background;
Man ladders;
PFont font1;
int time;
boolean run;
boolean newBarrel;
int barrelTotal;
Barrel[] barrel = new Barrel[100];
void setup() {
newBarrel = false;
run = true;
barrelTotal = 1;
time = millis();
size(800, 800);
Man = new Man();
background = new Man();
ladders = new Man();
for (int i = 0; i < barrel.length; i++) {
barrel[i] = new Barrel();
}
}
void draw() {
if (run == true) {
for (int i = 0; i < barrel.length; i++) {
if ((Man.bottom-10 >= barrel[i].top)&&(Man.bottom-10 <= barrel[i].bottom)&&(Man.Ladder == barrel[i].randomLadder)) {
print("GAME OVER!");
run = false;
}
if ((Man.top >= barrel[i].top)&&(Man.top <= barrel[i].bottom)&&(Man.Ladder == barrel[i].randomLadder)) {
print("GAME OVER!");
run = false;
}
}
}
if (run == true) {
background.createBackground();
Man.ladders();
Man.movement();
Man.createMan();
//spawns a barrel every second
if (millis()> time + 10) {
newBarrel = false;
print(" " + barrelTotal + " ");
time = time + 10;
barrelTotal = barrelTotal+1;
newBarrel = true;
}
for (int i = 0; i < barrelTotal; i++) {
if (newBarrel == true) {
}
barrel[i].gravity();
barrel[i].createBarrel();
}
//if(barrelTotal == 100){
//for (int i = 0; i < 50; i++){
// barrel[i] = "???";
//}
//}
}
}
Use an ArrayList instead of a native array. ArrayList will expand capacity as needed, whereas an array is fixed size and cannot be changed (you'd need to create a new larger array each time, which under the covers is what an ArrayList handles for you).
You can use ArrayList for this. You will change
// from
Barrel[] barrel = new Barrel[100]; // i suggest naming it to barrels instead of barrel
// to
ArrayList<Barrel> barrel = new ArrayList<>();
// or better
List<Barrel> barrel = new ArrayList<>();
// from
for (int i = 0; i < barrel.length; i++) {
barrel[i] = new Barrel();
}
// to
for (int i = 0; i < barrel.length; i++) {
barrel.add(new Barrel());
}
// from
barrel[i].<some-method()/attribute>
// to
barrel.get(i).<some-method()/attribute>
// etc
I highly recommend this for getting started with lists
https://docs.oracle.com/javase/tutorial/collections/interfaces/list.html
I have to backtracking with numbers in a list that represent restrictions, such as: "x1 + x2> = 1". And if it meets all the conditions, that array is added to another array, in addition there is another list that represents the sum that I must make with all the variables "x1 + x2 + x3 + x4" and with that search for the one with the minimum value.
good what I should do in backtraking is to make a binary matrix with all the possibilities that the restrictions meet. What I have done is this but I get the error: "Exception in thread" main "java.lang.IndexOutOfBoundsException: Index 2 out of bounds for length 0" and I don't know where my problem is.
import java.util.ArrayList;
public class Pra_hacer_pruebas {
public static void main(String[] args) {
Pra_hacer_pruebas a = new Pra_hacer_pruebas();
ArrayList<Integer> conf1= new ArrayList<>(); // conf1 is the list that will contain one of the possibilities that may or may not be added to the binary matrix.
ArrayList<ArrayList<Integer>>pos_v = new ArrayList<>();// pos_v is where the possibilities will be added, binary matrix
int[][] restric = new int[2][2];// restric is the list with restrictions
restric[0][0]=2;
restric[0][1]=1;
restric[1][0]=4;
restric[1][1]=2;
for(int t=0;t<4;t++){
conf1.set(t, -1);
}
//System.out.println(conf.get(i));
a.binario(conf1,restric,0,0,0,pos_v,0,4,-1);
}
public void binario(ArrayList<Integer> conf1, int[][] restric, int suma,int filas,int columnas,ArrayList<ArrayList<Integer>> pos_validas,int posicion, int cont,int bin){
//filas = rows, suma= sum is to see if it meets the condition, columnas = columns, pos_validas = pos_v, posicion is to advance the rows of the matrix, cont: is the amount of different variables, bin is the binary variable
Boolean booleano = false; // booleano is the flag that if it is true it is because there was a null position (-1)
for (int[] restric1 : restric) {
suma=0;
for (int co = 0; co < restric1.length; co++) {
if ((conf1.get(restric1[co]) == 1) || (conf1.get(restric1[co]) == 0)) {
suma = suma + conf1.get(restric1[co]);
} else {
booleano = true;
}
}
if (booleano == false) {
if (suma < 1){
break;
}
}
}
if (booleano == false) {
pos_validas.set(posicion, conf1);
posicion++;
}
for (int f = 0; f < cont; f++) {
if (conf1.get(f) < 1) {
bin++;
conf1.set(f, bin);
binario(conf1,restric,suma,filas,columnas,pos_validas,posicion,cont,bin);
}
bin--;
}
}
}
Try add method. Even if you create ArrayList with initialCapacity, It won't works as you intended. If you print ArrayList size before set, You can check it.
System.out.println(conf1.size());
for(int t=0; t<4; t++){
conf1.set(t, Integer.valueOf(-1));
}
Modify code to use add
for(int t=0; t<4; t++){
conf1.add(-1);
}
your Arraylist objects start out as empty objects. YOu can't call .set() on them at all: Those UPDATE existing entries, they don't make new ones. Try add.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I'm trying to code a battleship game and im getting a weird error when i run it: Exception in thread "main" java.lang.NullPointerException
at Caculations.findShip(Caculations.java:29)
at Board.main(Board.java:60)
Please help im stuck and i dont know how to continue! Here is my code: (Note, its in 2 class files in my eclipse work enviorment)
public class Board {
public static void main(String[] args) {
boolean continuePlay = true;
int[][] board = new int[10][10]; // creating 2d array 'board'
char[][] boardGraphical = new char[10][10]; // creating 2d array 'board
// this time the visual
for (int x = 0; x < 10; x++) { // for within for //initializing elements
// in both boards using double for
// method
for (int y = 0; y < 10; y++) {
board[x][y] = 0;
boardGraphical[x][y] = 'o';
System.out.println("Board element " + x + " " + y // printing
// initialized
// elements
// here
+ " initialized");
}
}
/*
* 1) Make user ships 1 and computer ships 2 (all numbers other than 0 =
* true)
*
* 2) Make it where if the computer gets a hit on a '1' than it sets
* that value to like a 3 or something so it knows when the ship is
* sunk. So in a if it does if([x][y] && [x][y])
* System.out.println("You sunk my ship!");
*
* 3) REMEMBER YOU CAN DO MULTIPLE IFS INSIDE IFS FOR MULTIPLE
* CONDITIONS. 4) declare ships here!
*
* 5) PUT STUFF IN A WHILE LOOP SO COMP CAN KEEP GOING
*/
board[3][3] = 1; // declaring a battleship. Very important.
board[3][4] = 1;
board[3][5] = 1;
boardGraphical[3][3] = 's';
boardGraphical[3][4] = 's';
boardGraphical[3][5] = 's';
while (continuePlay == true) { // while loop so that computer keeps
// guessing
// WITHIN THIS LOOP KEEP REPRINTING THE BOARD
double computerChoiceXd = Math.floor(Math.random() * 10); // using
// Math.random
// functions
// for
// computers
// first
// guess
// to be
// a
// random
// num
double computerChoiceYd = Math.floor(Math.random() * 10);
int computerChoiceX = (int) computerChoiceXd;
int computerChoiceY = (int) computerChoiceYd;
if (board[computerChoiceX][computerChoiceY] == 1) { // checking if
// math.random
// landed on a
// ship point
System.out.println("Computer got a hit at " + computerChoiceX
+ " " + computerChoiceY);
board[computerChoiceX][computerChoiceY] = 2; // setting the
// point as 2 or
// 'hit'
boardGraphical[computerChoiceX][computerChoiceY] = 'H';
for (int row = 0; row < 10; row++) { // printing out graphical
// board using the same
// method as when
// intializing
for (int col = 0; col < 10; col++) {
System.out.print(boardGraphical[row][col]);
}
System.out.println(" "); // spacer for printing
}
Caculations test = new Caculations(computerChoiceX, // Creating
// a new
// object of
// calculation
computerChoiceY, board);
test.findShip();
// break;
if (board[3][3] == 2) { // checking to see if ship is sunk using
// a triple if statement
if (board[3][4] == 2) {
if (board[3][5] == 2) {
System.out.println("Battleship sunk!");
continuePlay = false; // if so than it breaks out of
// loop to end the game
break;
}
}
}
} else if (board[computerChoiceX][computerChoiceY] == 0) { // otherwise
// if
// the
// area
// is a
// 0 or
// 'unmarked'
System.out.println("Computer missed at " + computerChoiceX
+ " " + computerChoiceY);
boardGraphical[computerChoiceX][computerChoiceY] = 'x'; // mark
// area
// as a
// miss
for (int row = 0; row < 10; row++) { // print out board
for (int col = 0; col < 10; col++) {
System.out.print(boardGraphical[row][col]);
}
System.out.println(" ");
}
}
}
}
}
public class Caculations {
int xValue;
int yValue;
int[][] myArray;
int[][] storage = new int[10][10];
boolean xAxisChangeP;
boolean yAxisChangeP;
boolean xAxisChangeN;
boolean yAxisChangeN;
boolean notSunk;
Caculations(int x, int y, int[][] myArray) {
xValue = x;
yValue = y;
xAxisChangeP = true;
yAxisChangeP = true;
xAxisChangeN = true;
yAxisChangeN = true;
notSunk = true;
}
void findShip() {
while (notSunk == true) {
// 1
while (xAxisChangeP == true) {
if (myArray[xValue + 1][yValue] == 1) {
myArray[xValue + 1][yValue] = 2;
if (myArray[3][3] == 2) {
if (myArray[3][4] == 2) {
if (myArray[3][5] == 2) {
System.out.println("Battleship sunk!");
notSunk = false;
}
}
}
continue;
}
else {
xAxisChangeP = false;
}
}
while (xAxisChangeN == true) {
if (myArray[xValue - 1][yValue] == 1) {
myArray[xValue - 1][yValue] = 2;
if (myArray[3][3] == 2) {
if (myArray[3][4] == 2) {
if (myArray[3][5] == 2) {
System.out.println("Battleship sunk!");
notSunk = false;
}
}
}
continue;
}
else {
xAxisChangeN = false;
}
}
// 1
while (yAxisChangeP == true) {
if (myArray[xValue][yValue + 1] == 1) {
myArray[xValue][yValue + 1] = 2;
if (myArray[3][3] == 2) {
if (myArray[3][4] == 2) {
if (myArray[3][5] == 2) {
System.out.println("Battleship sunk!");
notSunk = false;
}
}
}
continue;
}
else {
yAxisChangeP = false;
}
}
while (yAxisChangeN == true) {
if (myArray[xValue][yValue - 1] == 1) {
myArray[xValue][yValue - 1] = 2;
if (myArray[3][3] == 2) {
if (myArray[3][4] == 2) {
if (myArray[3][5] == 2) {
System.out.println("Battleship sunk!");
notSunk = false;
}
}
}
continue;
}
else {
yAxisChangeN = false;
}
}
}
}
}
Have you initialized myarray? Best is debug your code to see, which statement throws the exception. In eclipse you can add NullPointerExeption as your breakpoint and debug.
You use myArray, but you never initialize it.
public class Caculations {
int xValue;
int yValue;
int[][] myArray; // array declared but never initialized
// ....
void findShip() {
while (notSunk == true) {
// 1
while (xAxisChangeP == true) {
if (myArray[xValue + 1][yValue] == 1) // then you use it here
Solution: initialize variables before using.
More importantly, you need to learn the general concepts of how to debug a NPE (NullPointerException). You should critically read your exception's stacktrace to find the line of code at fault, the line that throws the exception, and then inspect that line carefully, find out which variable is null, and then trace back into your code to see why. You will run into these again and again, trust me.
In your constructor for Calculations, you never initialized myArray:
Caculations(int x, int y, int[][] myArray) {
xValue = x;
yValue = y;
xAxisChangeP = true;
yAxisChangeP = true;
xAxisChangeN = true;
yAxisChangeN = true;
notSunk = true;
this.myArray = myArray; //Add this line
}
This is a direct answer to your problem, but all in all, you should do some research regarding the meaning behind the exception that was thrown so you understand what it means.
Why this problem happened
In Java, all objects and primitives, if not initialized manually, are given a default value.
For default values of primitives, check this: Primitive Data Types
In case of non-primitive types - such as Object, String, Thread, etc, as well as any user-defined class (i.e. Calculations) and also arrays (i.e. myArray) - the default value is null.
With that in mind, inside your constructor, as exemplified above, you have not initialized myArray, which means that when this variable was accessed for the first time, the value returned was null.
So, what's the problem with null?
Well, by itself, it does no harm. It's there. It doesn't bother you. Until you decide to use a variable that doesn't have an object assigned to it, but somehow you forget that and treat it as if it held something like a String or an array.
That's when Java will tell you: "Hey! There's no object here. I can't work like this. Let's throw an exception!".
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm not sure what's going on, but in the console I have a red 'stop' square that i can click to stop my program from running (Eclipse IDE) and my program is just running and the square stays red..?
EDIT:
my maze:
WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW
WSOOOOOOOOOOOOOOWOOOOOOOOOOOOOOOOOWOOOOOOOOOOOOOOOWOOOOOOW
WWOOOOOOOOOOOOOWWWWWWWWWWWWWOOOOOOOOOOWWWWWWWWWWWWWOOOOOOW
WWWWWWOOOOOOOOOOOOWWWWWWWOOOOOOOOOOOOWWWWWWWWWWWWWWWWOOOOW
WOOOOOOWWWWWWWWWWWWWWOOOOOOOOOOOWWWWWWWWOOOOOOOOOOOOOOOWWW
WOOOOWWWWWWWOOOOOOWWWWOOOOOOWWWWWWWWWWWOOOOWWWWWWWWWOWWWWW
WOOOWWWWWWWWWWWWOOWWWWWWWWWWWWOOOOOOOOOOOOWWWWWWWWWOOOOOWW
WOOWWWWWWWWWWWWWOOWWWWWWWWWWWWWWWWWOOOOOOOWWWWWWWWWWWWOOOW
WOWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWOOOOOOOWWWWWWWWWWWOOW
WOWWWWWWWWWWWWWOOOOOOOOOOOOOOOOOOOOOOOOOOOOWWWWWWWWWWWWOOW
WOOOOOOOOOOOOOOOOWWWWOOOOOOOOWWWWWWWOOOOOOWWWWWWWWWWWWWWFW
WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW
EDIT: here is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Stack;
import java.awt.Point;
public class MazeExplorer {
static Point startPoint = new Point();
static Point finishPoint = new Point();
final static int mazeHeight = 12;
final static int mazeWidth = 58;
static char[][] mazePoints = new char[mazeHeight][mazeWidth];
Stack<Point> pointsNotTraversed = new Stack<Point>();
Point pt = new Point();
static HashSet<Point> previousLocations = new HashSet<Point>();
static Stack<Point> nextPoints = new Stack<Point>();
public static void main(String[] args) throws FileNotFoundException{
System.out.println("Please enter the file name of your Maze");
Scanner console = new Scanner(System.in);
File f = new File(console.nextLine());
Scanner sc = new Scanner(f);
if(!sc.hasNextLine()){
System.out.println("Sorry, please enter a file name with the extension, that contains a maze!");
}
System.out.println("So, you want to know if your maze is solvable.....?");
for (int row = 0; row < mazeHeight && sc.hasNext(); row++) {
final String mazeRow = sc.next(); //Get the next row from the scanner.
mazePoints[row] = mazeRow.toCharArray(); //Convert the row into a char[].
}
//identify the finish point
for(int i = 0; i < mazeHeight; i++){
for(int j = 0; j<mazeWidth; j++){
if(mazePoints[i][j] == 'F'){
finishPoint = new Point(i, j);
}
}
}
// Identify the start point
for(int i = 0; i< mazeHeight; i++){
for(int j = 0; j < mazeWidth; j++){
if(mazePoints[i][j] == 'S'){
startPoint = new Point(i , j);
}
}
}
isTraversable(startPoint);
}
public static boolean isTraversable(Point current){
boolean isSolvable = false;
nextPoints.push(current);
do {
if(current.y < 11) {
if((mazePoints[current.y + 1][current.x] != ' ') && (mazePoints[current.y + 1][current.x] != 'W') ){ // below direction
nextPoints.push(new Point(current.y + 1, current.x));
mazePoints[current.y + 1][current.x] = ' ';
isTraversable(nextPoints.pop());
}
}
if(current.y > 0){
if (mazePoints[current.y - 1][current.x] != ' ' && mazePoints[current.y - 1][current.x] != 'W' ){ //up dir
nextPoints.push(new Point(current.y - 1, current.x));
mazePoints[current.y - 1][current.x] = ' '; //'X' marks where you've already been
isTraversable(nextPoints.pop());
}
}
if(current.x < 57){
if(mazePoints[current.y][current.x + 1] != ' ' && mazePoints[current.y][current.x + 1] != 'W'){ // to the right
nextPoints.push(new Point(current.y, current.x + 1));
mazePoints[current.y][current.x + 1] = ' ';
isTraversable(nextPoints.pop());
}
}
if(current.x > 0){
if(mazePoints[current.y][current.x - 1] != ' ' && mazePoints[current.y][current.x - 1] != 'W') { // to the left
nextPoints.push(new Point(current.y, current.x - 1));
mazePoints[current.y][current.x - 1] = ' ';
isTraversable(nextPoints.pop());
}
}
if(current.equals(finishPoint)){
isSolvable = true;
System.out.println("MAZE IS SOLVABLE, YAHOOOOOO!!!!");
}
} while(!current.equals('F') && !nextPoints.isEmpty());
return isSolvable;
}
}
As I suggested before, you just need to reconfigure your recursive method. I took the liberty of doing this but if you ever want to learn how to program you'll want to try and solve problems like these on your own. Or try to understand the logic of your solution before you start coding.
Your main problem is that you don't know what direction you want to go in with the method before you just jumped in and that was causing all sorts of errors with different things not being compatible with each other.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Stack;
import java.awt.Point;
public class TestCode {
static Point startPoint = new Point();
static Point finishPoint = new Point();
final static int mazeHeight = 12;
final static int mazeWidth = 58;
static char[][] mazePoints = new char[mazeHeight][mazeWidth];
Stack<Point> pointsNotTraversed = new Stack<Point>();
Point pt = new Point();
static HashSet<Point> previousLocations = new HashSet<Point>();
static Stack<Point> nextPoints = new Stack<Point>();
public static void main(String[] args) throws FileNotFoundException{
System.out.println("Please enter the file name of your Maze");
Scanner console = new Scanner(System.in);
File f = new File(console.nextLine());
Scanner sc = new Scanner(f);
if(!sc.hasNextLine()){
System.out.println("Sorry, please enter a file name with the extension, that contains a maze!");
}
System.out.println("So, you want to know if your maze is solvable.....?");
for (int row = 0; row < mazeHeight && sc.hasNext(); row++) {
final String mazeRow = sc.next(); //Get the next row from the scanner.
mazePoints[row] = mazeRow.toCharArray(); //Convert the row into a char[].
}
//identify the finish point
for(int i = 0; i < mazeHeight; i++){
for(int j = 0; j<mazeWidth; j++){
if(mazePoints[i][j] == 'F'){
finishPoint = new Point(i, j);
}
}
}
// Identify the start point
for(int i = 0; i< mazeHeight; i++){
for(int j = 0; j < mazeWidth; j++){
if(mazePoints[i][j] == 'S'){
startPoint = new Point(i , j);
}
}
}
System.out.println(isTraversable(startPoint));
}
public static boolean isTraversable(Point current){
mazePoints[current.x][current.y] = ' ';
if(current.y < 56 && current.y > 0 && current.x > 0 && current.x < 11){
if (mazePoints[current.x - 1][current.y] == 'O'){ // Up dir
Point upPoint = new Point(current.x-1, current.y);
nextPoints.push(upPoint);
}
if(mazePoints[current.x+1][current.y] == 'O'){ // Down dir
Point downPoint = new Point(current.x+1, current.y);
nextPoints.push(downPoint);
}
if(mazePoints[current.x][current.y + 1] == 'O'){ // to the right
Point rightPoint = new Point(current.x, current.y+1);
nextPoints.push(rightPoint);
}
if(mazePoints[current.x][current.y - 1] == 'O'){ // to the left
Point leftPoint = new Point(current.x, current.y-1);
nextPoints.push(leftPoint);
}
if(mazePoints[current.x - 1][current.y] == 'F' ||
mazePoints[current.x + 1][current.y] == 'F' ||
mazePoints[current.x][current.y - 1] == 'F' ||
mazePoints[current.x][current.y + 1] == 'F'){
System.out.println("MAZE IS SOLVABLE, YAHOOOOOO!!!!");
return true;
}
}
if(nextPoints.isEmpty()){
return false;
}
else{
current = nextPoints.pop();
}
return(isTraversable(current));
}
}
With the maze input:
WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW
WSOOOOOOOOOOOOOOWOOOOOOOOOOOOOOOOOWOOOOOOOOOOOOOOOWOOOOOOW
WWOOOOOOOOOOOOOWWWWWWWWWWWWWOOOOOOOOOOWWWWWWWWWWWWWOOOOOOW
WWWWWWOOOOOOOOOOOOWWWWWWWOOOOOOOOOOOOWWWWWWWWWWWWWWWWOOOOW
WOOOOOOWWWWWWWWWWWWWWOOOOOOOOOOOWWWWWWWWOOOOOOOOOOOOOOOWWW
WOOOOWWWWWWWOOOOOOWWWWOOOOOOWWWWWWWWWWWOOOOWWWWWWWWWOWWWWW
WOOOWWWWWWWWWWWWOOWWWWWWWWWWWWOOOOOOOOOOOOWWWWWWWWWOOOOOWW
WOOWWWWWWWWWWWWWOOWWWWWWWWWWWWWWWWWOOOOOOOWWWWWWWWWWWWOOOW
WOWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWOOOOOOOWWWWWWWWWWWOOW
WOWWWWWWWWWWWWWOOOOOOOOOOOOOOOOOOOOOOOOOOOOWWWWWWWWWWWWOOW
WOOOOOOOOOOOOOOOOWWWWOOOOOOOOWWWWWWWOOOOOOWWWWWWWWWWWWWOFW
WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW
Yields the following output:
So, you want to know if your maze is solvable.....?
MAZE IS SOLVABLE, YAHOOOOOO!!!!
true
I imported the file a different way, but you can change that back to whatever method you use previously.
Might be that you've started multiple programs and you have the "Show Console When Standard Output Changes" Not sure, but that explains one scenario. If you start task manager and find the program there you could try terminating it that way.
If it's stuck running and never completes you could try running your program in the Eclipse debugger, without any breakpoints.
Open the Debug tab (Open in from Window > Show View > Debug), suspend the thread by right clicking 'Thread [main] (Running)' and selecting 'Suspend'.
Then work your way up from the bottom of the stack, hopefully this will narrow it down enough for you to find where it blocks.
import java.util.Scanner;
import java.util.Stack;
public class test5 {
private int numRows;
private int numCols;
public test5(){
Scanner input = new Scanner(System.in);
System.out.println("Enter number of rows: ");
numRows = input.nextInt();
System.out.println("Enter number of cols: ");
numCols = input.nextInt();
Stack<Point>stack = new Stack<Point>();
stack.push(new Point(0,0));
while(!stack.isEmpty()){
if(currentPath(stack.pop(),stack)){
System.out.println("Maze is solvable");
}
}
}
public static void main(String[]args){
new test5();
}
private boolean currentPath(Point point, Stack<Point>stack){
int currentRow = point.getRow();
int currentCol = point.getCol();
while(currentRow!=numRows-1 || currentCol!=numCols-1){
boolean canGoRight = canGoRight(currentRow,currentCol);
boolean canGoUp = canGoUp(currentRow,currentCol);
boolean canGoDown = canGoDown(currentRow,currentCol);
if(canGoRight){
if(canGoUp){
stack.push(new Point(currentRow-1,currentCol));
}
if(canGoDown){
stack.push(new Point(currentRow+1,currentCol));
}
currentCol = currentCol+1;
}
else{
if(canGoUp){
if(canGoDown){
stack.push(new Point(currentRow+1,currentCol));
}
currentRow = currentRow-1;
}
else if(canGoDown){
currentRow = currentRow+1;
}
else{
return false;
}
}
}
return true;
}
private boolean canGoUp(int row, int col){
return row-1>=0;
}
private boolean canGoRight(int row, int col){
return col+1<numCols;
}
private boolean canGoDown(int row, int col){
return row+1<numRows;
}
class Point{
private int row;
private int col;
public Point(int row, int col){
this.row = row;
this.col = col;
}
public int getRow(){
return row;
}
public int getCol(){
return col;
}
}
}
package homework3;
public class DoubleMatrix
{
private double[][] doubMatrix;
public DoubleMatrix (int row, int col)
{
if(row > 0 & col > 0)
{
makeDoubMatrix(1,1);
}
else
{
row = 1;
col = 1;
}
}
public DoubleMatrix(double[][] tempArray)
{
int k = tempArray.length;
if(tempArray != null)
{
for(int i = 0; i < tempArray.length;i++)
{
if(k== tempArray[i].length)
{
}
}
}
else
{
makeDoubMatrix(1,1);
}
}
}
This is what i was supposed to start my assignment with:
Write a class called DoubleMatrix in which you declare a 2-dim. array of doubles (I'm calling it doubMatrix) as a private instance variable. Include the following constructors or instance methods (NO static METHODS HERE):
constructor with an int for the first dimension (be sure it's > 0, set to 1 if not), and an int for the second dimension (be sure it's > 0, set to 1 if not) and call the makeDoubMatrix private instance method (see below)
another constructor with a 2-dim. array of doubles as its parameter (assign if parameter isn't null AND if each row has the same length as the other rows), otherwise, call makeDoubMatrix with 1, 1)
can someone check that if I did the check in second constructor right? Also I left out the assigning statement in the second if because I don't know what to assign can anyone tell me what to assign since the problem only say assign but didn't say to assign to what value.
You would have to check for each row first, whether they are of same length or not. You can maintain a boolean flag variable, which you can set to false as soon as you see that the current row is not the same length as the next row.
You can try the below code, and test whether it works: -
public DoubleMatrix(double[][] tempArray)
{
if(tempArray != null)
{
boolean flag = true;
for(int i = 0; i < tempArray.length - 1;i++)
{
// Check each row with the next row
if(tempArray[i].length != tempArray[i + 1].length)
{
// as you find the row length not equal, set flag and break
flag = false;
break;
}
}
if (flag) {
doubleMatrix = tempArray;
} else {
makeDoubleMatrix(1,1);
}
} else {
makeDoubleMatrix(1, 1);
}
}
public DoubleMatrix(double[][] tempArray)
{
//Calling tempArray.length if tempArray is null will get you an error
if(tempArray != null)
{
for(int i = 0; i < tempArray.length;i++)
{
for(int j=0;j<tempArray[i].length;j++)
{
doubleMatrx[i][j] = tempArray[i][j];
}
}
}
else
{
makeDoubMatrix(1,1);
}
}
Also in Java a 2D array will always have the same number of columns in each row since it's declaration is something like int bob[][] = new int[a][b]