for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
visBoard[i][j] = "[ ]";
board[i][j] = 0;
check[i][j] = false;
}
}for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
System.out.print(visBoard[i][j]);
}System.out.print("\n");
}
//Getting Names
System.out.println("Player 1 - Enter your name");
play1 = sc.nextLine();
System.out.println("Player 2 - Enter your name");
play2 = sc.nextLine();
//
moves = 0;
symbol = " X ";
do{
do{
//Get Coords
System.out.println("X Coordinate");
xcoord = sc.nextInt() -1;
System.out.println("Y Coordinate");
ycoord = sc.nextInt() -1;
if(check[xcoord][ycoord] == true){
System.out.println("Not a valid move!");
}
}while(check[xcoord][ycoord] == true);
//Making move
check[xcoord][ycoord] = true;
visBoard[xcoord][ycoord] = symbol;
if(symbol.equals(" X ")){
board[xcoord][ycoord] = 1;
}else if(symbol.equals(" O ")){
board[xcoord][ycoord] = 5;
}else{
System.out.println("You've messed up James");
}
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
System.out.print(visBoard[i][j]);
}System.out.print("\n");
}
//Check if game has won
//columns
total = 0;
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
total = total + board[j][i];
}if(total == 15 || total == 3){
gamewon = true;
}
}total = 0;
//rows
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
total = total + board[i][j];
}if(total == 15 || total == 3){
gamewon = true;
}
}total = 0;
//diagonals
for(int i = 0; i < 3; i++){
total = total + board[i][i];
}if(total == 15 || total == 3){
gamewon = true;
}total = 0;
diag = 2;
for(int i = 0; i < 3; i++){
total = total + board[i][diag];
diag--;
}if(total == 15 || total == 3){
gamewon = true;
}
moves++;
if(gamewon == false){
if(moves == 9){
System.out.println("Game has been drawn! No one wins!");
}else{
mod = moves % 2;
if(mod == 0){
symbol = " X ";
}else{
symbol = " O ";
}
}
}
}while(gamewon == false || moves != 9);
if(gamewon == true){
if(symbol.equals(" X ")){
System.out.println("Winner is "+play1);
}else{
System.out.println("Winner is "+play2);
}
}else{
System.out.println("Game is drawn");
}
}
}
This is a further question from a previous question I had. This game won't end until moves reaches 9 even though the while loop should stop once someone has won. The boolean will turn true, but it will continue to loop.
How do I fix this issue with keeping the while condition, and possibly without using breaks?
You need an and not an or
while(gamewon == false && moves != 9);
Reading that to yourself it says while there is no winner and we are not at move 9. However it's usually better form to code your loops to check that you haven't exceeded a bound rather than you have hit the bound exactly, and it is also nicer to simply test the boolean directly so the following is more stylish:
while(!gamewon && moves < 9);
while(gamewon == false || moves != 9)....
This tells the loop to execute while game isnt won, or moves are not 9. For it to end, BOTH conditions need to change, the game needs to be ended AND moves needs to be 9.
Change your || operator to &&. This way the game will keep going while the game is not won AND the moves is not 9. It seems a bit strange but if you can follow the logic, you'll see that you need the AND operator.
Therefore, you're looking for:
while(gamewon == false && moves != 9)
Related
I am solving this problem on code forces.
https://codeforces.com/contest/1675/problem/B
The break statement I have doesn't break out of the while loop.
When I use this input:
It outputs -1 one twice in the same case, which shows that the break statement isn't taking me outside the loop?
Why is this happening?
public class vanita {
public static void main (String[]args) {
Scanner in = new Scanner(System.in);
int cases = in.nextInt();
for (int i = 0; i < cases; i++) {
boolean test = true;
int arrLength = in.nextInt();
int arr[] = new int[arrLength];
for (int j = 0; j < arrLength; j++) {
arr[j] = in.nextInt();
}
int operations = 0;
int after;
for (int j = arrLength-1; j >= 1 ; j--){
after = arr[j-1];
while (arr[j] <= after) {
arr[j-1] = (int)Math.floor(arr[j-1]/2);
after = arr[j-1];
operations++;
if (arr[j] == 0 && arr[j-1] == 0) {
//System.out.println("current: " + arr[j]);
//System.out.println("after: " + arr[j-1]);
//System.out.println("Case " + i);
System.out.println("-1");
test = false;
break;
}
}
}
for (int s = 0; s < arrLength; s++) {
//System.out.print(arr[s] + " ");
}
//System.out.println(" ");
if (test == true) {
System.out.println(operations);
}
}
}
}
i think it breaks out of the inner while loop, but not the outer for loop. So the inner while loop runs multiple times.
Problems
Normally a break; will always break out of the most recent loop. If you can't break out of your loop, the problem is your algorithm or your condition.
Solutions
First, always debug to see if you enter your if statement.
Second, use something else as condition of your while loop. You could use a boolean and change its value to break the while condition. Ex:
boolean hasFoundDuplicate = false;
while(!hasFoundDuplicate){
arr[j-1] = (int)Math.floor(arr[j-1]/2);
after = arr[j-1];
operations++;
if(arr[j] == 0 && arr[j-1] == 0){
hasFoundDuplicate = true;
}
}
Hey guys so my homework was to:
1)Prompt the user to enter the number of cells C
2)Declare an integer array cell[] with C elements
3)Prompt the user to enter the number of time steps N
3)Prompt the user to enter the index of cells that contain 1(enter negative index to finish)
4)Run the cellular automaton for N time steps, using the rules defined above
5)On each time step, display the cells, printing a ‘#’ if the cell contains a 1,
a space if the cell contains a 0
A desired output would be:
Enter number of cells (<= 80): 10
Enter number of time steps: 10
Enter the index of occupied cells (negative index to end): 4 6 -1
0123456789
# #
####
## #
### ##
# ####
### #
# # ##
######
# #
# ##
# ###
My code so far is this:
import java.util.Scanner;
class P7{
public static void main(String[] args){
int i, N, C, index;
Scanner in = new Scanner(System.in);
System.out.println("Enter number of cells(<=80):");
C = in.nextInt();
int[] cell = new int[C];
System.out.println("Enter number of time steps:");
N = in.nextInt();
System.out.println("Enter the index of occupied cells(-num to end):");
for(i = 0; i < C; i++){
cell[i] = 0;
}
while(true){
index = in.nextInt();
if(index < 0){
break;
}
cell[index] = 1;
}
for(i = 0; i < N; i++)
updateCells(cell);
displayCells(cell);
}
public static void updateCells(int array[]){
int i;
int[] temp = new int[array.length];
for(i = 1; i < array.length - 1; i++){
if(array[i]==1 && array[i-1]==1 && array[i+1]==1)
temp[i] = 0;
else if(array[i]==1 && array[i-1]==1 && array[i+1]==0)
temp[i] = 1;
else if(array[i]==0 && array[i-1]==1 && array[i+1]==1)
temp[i] = 1;
else if(array[i]==0 && array[i-1]==1 && array[i+1]==0)
temp[i] = 0;
else if(array[i]==1 && array[i-1]==0 && array[i+1]==1)
temp[i] = 1;
else if(array[i]==1 && array[i-1]==0 && array[i+1]==0)
temp[i] = 1;
else if(array[i]==0 && array[i-1]==0 && array[i+1]==1)
temp[i] = 1;
else if(array[i]==0 && array[i-1]==0 && array[i+1]==0)
temp[i] = 0;
}
for(i = 0; i < array.length; i++){
array[i] = temp[i];
}
}
public static void displayCells(int data[]){
int i;
for(i=0;i < data.length; i++){
if(data[i] == 1)
System.out.println("#");
else if(data[i] == 0)
System.out.println(" ");
}
}
}
This is my current output:
Enter number of cells(<=80): 10
Enter number of time steps: 3
Enter the index of occupied cells(-num to end):
1
2
3
4
-1
#
#
#
#
Any and all help will be appreciated :D
I actually don't understand what you trying to do, try this if that might would help. If you have the question in written or any pdf, then I can probably tell. Best
import java.util.Scanner;
public class P7{
public static void main(String[] args){
int i, N, C, index;
Scanner in = new Scanner(System.in);
System.out.println("Enter number of cells(<=80):");
C = in.nextInt();
int[] cell = new int[C];
System.out.println("Enter number of time steps:");
N = in.nextInt();
System.out.println("Enter the index of occupied cells(-num to end):");
for(i = 0; i < N; i++){
cell[i] = 0;
}
while(true){
index = in.nextInt();
if(index < 0){
break;
}
cell[index] = 1;
}
for(i = 0; i < N; i++)
updateCells(cell);
displayCells(cell);
}
public static void updateCells(int cell[]){
int i;
int[] temp = new int[cell.length];
for(i = 1; i < cell.length - 1; i++){
if(cell[i]==1 && cell[i-1]==1 && cell[i+1]==1)
temp[i] = 0;
else if(cell[i]==1 && cell[i-1]==1 && cell[i+1]==0)
temp[i] = 1;
else if(cell[i]==0 && cell[i-1]==1 && cell[i+1]==1)
temp[i] = 1;
else if(cell[i]==0 && cell[i-1]==1 && cell[i+1]==0)
temp[i] = 0;
else if(cell[i]==1 && cell[i-1]==0 && cell[i+1]==1)
temp[i] = 1;
else if(cell[i]==1 && cell[i-1]==0 && cell[i+1]==0)
temp[i] = 1;
else if(cell[i]==0 && cell[i-1]==0 && cell[i+1]==1)
temp[i] = 1;
else if(cell[i]==0 && cell[i-1]==0 && cell[i+1]==0)
temp[i] = 0;
}
for(i = 0; i < cell.length; i++){
cell[i] = temp[i];
}
}
public static void displayCells(int cell[]){
int i;
for(i=0;i < cell.length; i++){
if(cell[i] == 1)
System.out.print("#");
else if(cell[i] == 0)
System.out.print(" ");
}
}
}`enter code here`
This is a movie ticket theatre seller program. The task is create a method that takes the price of the user's input, finds the first seat and replaces it with a 0, denoting a sold seat. I keep fiddling with it but it keeps wanting to change all instances of the price input to 0 instead of the first found.
public boolean getByPrice(int price) {
boolean retVal = false; //initially false, have not found
System.out.println("You chose to buy a ticket with price: $" + price);
if (price == 10) {
for (int i = 0;i<NUM_ROWS;i++) {
for (int j = 0; j<NUM_COLS; j++) {
if (seats[i][j] == 10) {
retVal = true;
seats[i][j] = 0;
}
pricesAvailable[0] = pricesAvailable[0] - 1;
}
}
}
if (price == 20) {
for (int i = 0; i<NUM_ROWS;i++) {
for (int j = 0; j<NUM_COLS;j++) {
if (seats[i][j] == 20) {
retVal = true;
seats[i][j] = 0;
}
pricesAvailable[1] = pricesAvailable[1] - 1;
}
}
}
if (price == 30) {
for (int i = 0; i<NUM_ROWS;i++) {
for (int j = 0; j<NUM_COLS; j++) {
if (seats[i][j] == 30) {
retVal = true;
seats[i][j] = 0;
}
pricesAvailable[2] = pricesAvailable[2] - 1;
}
}
}
if (price == 40) {
for (int i = 0; i<NUM_ROWS;i++) {
for (int j = 0; j<NUM_COLS;j++) {
if (seats[i][j] == 20) {
retVal = true;
seats[i][j] = 0;
}
pricesAvailable[3] = pricesAvailable[3] - 1;
}
}
}
if (price == 50) {
for (int i = 0; i<NUM_ROWS;i++) {
for (int j = 0; j<NUM_COLS;j++) {
if (seats[i][j] == 50) {
retVal = true;
price = 0;
}
pricesAvailable[4] = pricesAvailable[4] - 1;
}
}
}
return retVal;
}
Also, the other part is to implement the same type of method using location
public boolean getByLoc(int row, int col) {
boolean retVal = false; //initially false
System.out.println("You chose row: " + row + ", col: " + col);
//************YOUR SOLUTION GOES HERE************//
for (int i = 0;i<NUM_ROWS;i++) {
for (int j = 0; j<NUM_COLS; j++) {
}
}
return retVal; //return value
}
I am not sure how use to make the location method work at all
Your loop does not exit when you found a seat. You could use break like:
for (int i = 0; i<NUM_ROWS && !retVal; i++){
for (int j = 0; j<NUM_COLS && !retVal; j++){
if (seats[i][j] == 10){
retVal = true;
seats[i][j] = 0;
break;
}
}
if (retVal) break;
}
or you could add a condition to your loops like:
for (int i = 0; i<NUM_ROWS && !retVal; i++){
for (int j = 0; j<NUM_COLS && !retVal; j++){
...
}
}
I would also recomend to reduce the code duplication by having the same loop in multiple ifs. How about summarizing it like this? (I assumed the pricesAvailable should only be lowerd when a seat has been found)
if (price == 0) { throw new IllegalArgumentException("Not giving away freebies"); }
for (int i = 0; i<NUM_ROWS && !retVal; i++){
for (int j = 0; j<NUM_COLS && !retVal; j++){
if (seats[i][j] == price){
retVal = true;
seats[i][j] = 0;
pricesAvailable[(price/10)-1]--;
}
}
}
Edit: Of couse returning inside the loops would also work if this is all you want to do in this method:
if (price == 0) { throw new IllegalArgumentException("Not giving away freebies"); }
for (int i = 0; i<NUM_ROWS; i++){
for (int j = 0; j<NUM_COLS; j++){
if (seats[i][j] == price){
seats[i][j] = 0;
pricesAvailable[(price/10)-1]--;
return true;
}
}
}
return false;
You'll probably want to utilise a break; somewhere if you intend to keep your code as it is.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
http://www.c4learn.com/java/java-break-statement/
You need to break the for-loop when you have found a matching seat, otherwise it will continue to check all the other seats.
You have two nested loops, but you want to break out of both. There are a few ways to do this, but as this is relatively simple code, a label will suffice. Take a look at http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html.
As the comments have pointed out, this is obviously homework, so I won't post a full code listing, instead, here is a snippet:
rows:
for (int i = 0; i < NUM_ROWS; i++)
{
cols:
for (int j = 0; j < NUM_COLS; j++)
{
if (seats[i][j] == 30)
{
retVal = true;
seats[i][j] = 0;
}
pricesAvailable[2] = pricesAvailable[2] - 1;
break rows;
}
}
Also, please use braces around if-statements, it's just another way to introduce bugs.
That is because you keep looping even after you have found the first seat with that price. The best thing here would be to use a method, like below, and return after you're done with the first one. This will solve both your refactoring problems and your incorrect values:
public boolean findFirst(int cost){
for (int i = 0;i<NUM_ROWS;i++)
for (int j = 0; j<NUM_COLS; j++)
if (seats[i][j] == cost){
seats[i][j] = 0;
pricesAvailable[cost / 10 - 1] -= 1;
return true;
}
return false;
}
Then call it from your getByPrice function like this:
public boolean getByPrice(int price) {
boolean retVal = false; //initially false, have not found
System.out.println("You chose to buy a ticket with price: $" + price);
if (price == 10)
retval = findFirst(10);
//rest of the code...
You should break the loop as soon as the place is found. Otherwise you'll put 0 on all places that have the price == 10.
if (price == 10) {
for (int i = 0;i<NUM_ROWS;i++) {
for (int j = 0; j<NUM_COLS; j++) {
if (seats[i][j] == 10) {
retVal = true;
seats[i][j] = 0; //and here break/return.
}
pricesAvailable[0] = pricesAvailable[0] - 1;
}
}
}
Also your basically copying the same code 5 times. What if there were 100 different prices? Whould you copy that code 100 times?
You should consider putting the code that is duplicated inside a method and the variable part (price in this example) should be an input parameter.
Moreover variable pricesAvailable is quite problematic. First it's not named the best way. Maybe seatsAvailableAtPrice would sound better? And I don't think that array is the best container for that - you should try using Map where first integer would be the price, and the second would be the number of seats left for that price.
Map<Integer, Integer> seatsAvailableAtPrice = new HashMap<Integer, Integer>();
Putting it all together you could create a method like that:
private void reserveFirstAvailableSeatForPrice(final int price) {
for (int i = 0;i<NUM_ROWS;i++) {
for (int j = 0; j<NUM_COLS; j++) {
if (seats[i][j] == price) {
seats[i][j] = 0;
seatsAvailableAtPrice.put(price, seatsAvailableAtPrice.get(price) - 1);
return;
}
}
}
}
As for the second part - isn't that just checking if i=row and j=col? And if so making a reservation (setting price to 0)?
I'm trying to write a simple game in Java that creates a grid of dots using a 2d array for the user to move on. I've done that and I've gotten to the point where I'm asking the user for their movement selection, however, after that happens I want to reprint the grid with their old space empty, and with the 'o' in the space they moved to. I'm unsure how to go about reprinting the grid though, as when I first printed it I used an if statement to tell the loop where to not put dots. I'll post the code below, tips are greatly appreciated!
import java.util.Scanner;
import java.util.Random;
public class main {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
char[][] gridArray = new char[10][10];
int randomRow;
int randomCol;
int randomRow2;
int randomCol2;
String moveSelect;
boolean validInput = true;
int min = 0;
int max = 9;
Random tRNG = new Random();
randomRow = tRNG.nextInt(max - min + 1) + min;
randomCol = tRNG.nextInt(max - min + 1) + min;
randomRow2 = tRNG.nextInt(max - min + 1) + min;
randomCol2 = tRNG.nextInt(max - min + 1) + min;
gridArray[randomRow][randomCol] = 'o';
gridArray[randomRow2][randomCol2] = 'X';
for (int i = 0; i < gridArray.length; i++)
{
for (int j = 0; j < gridArray.length; j++)
{
if (gridArray[i][j] != gridArray[randomRow][randomCol] && gridArray[i][j] != gridArray[randomRow2][randomCol2])
{
gridArray[i][j] = '.';
}
System.out.print(gridArray[i][j]);
}
System.out.println("");
}
System.out.println("Enter a movement choice W A S or D");
do{
Scanner keyboard = new Scanner(System.in);
moveSelect = keyboard.nextLine();
if ( moveSelect.equals("w"))
{
gridArray[randomRow][randomCol] = gridArray[randomRow+1][randomCol];
gridArray[randomRow][randomCol] = ' ';
validInput = true;
}
else if ( moveSelect.equals("a"))
{
gridArray[randomRow][randomCol] = gridArray[randomRow][randomCol-1];
gridArray[randomRow][randomCol] = ' ';
validInput = true;
}
else if ( moveSelect.equals("s"))
{
gridArray[randomRow][randomCol] = gridArray[randomRow-1][randomCol];
gridArray[randomRow][randomCol] = ' ';
validInput = true;
}
else if (moveSelect.equals("d"))
{
gridArray[randomRow][randomCol] = gridArray[randomRow][randomCol+1];
gridArray[randomRow][randomCol] = ' ';
validInput = true;
}
else
{
System.out.println("Invalid Entry. Try again.");
validInput = false;
}
} while (validInput == false);
}
}
I think most of the problems come from general confusion about arrays. E.g. the line from the code block run when you press w:
gridArray[randomRow][randomCol] = gridArray[randomRow+1][randomCol];
sets the char value of the array at randomRow, randomCol (in this case an 'x') to the char value of the of the array space one row below it at randomRow+1, randomCol. And then the line of code after that:
gridArray[randomRow][randomCol] = ' ';
assigns a new value to that same space making the code above worthless! And in the end, randomRow and randomCol are never modified. (also you had some confusion about which way the x would move with a higher row value)
all you actually need to do in this code block is:
randomRow -= 1;
after this, you can simply reprint the whole grid with the printing code from before. Although there are other issues with this code that make it far from optimal. Also there are a similar problem in that if statement in the for loop that worked but led to problems later down the road. Simply rewriting it to fix all the things wrong, you get this:
char[][] gridArray = new char[10][10];
int randomRow;
int randomCol;
int randomRow2;
int randomCol2;
String moveSelect;
boolean validInput = true;
int min = 0;
int max = 9;
Random tRNG = new Random();
randomRow = tRNG.nextInt(max - min + 1) + min;
randomCol = tRNG.nextInt(max - min + 1) + min;
randomRow2 = tRNG.nextInt(max - min + 1) + min;
randomCol2 = tRNG.nextInt(max - min + 1) + min;
gridArray[randomRow][randomCol] = 'o';
gridArray[randomRow2][randomCol2] = 'X';
for (int i = 0; i < gridArray.length; i++)
{
for (int j = 0; j < gridArray.length; j++)
{
if (!((i == randomRow && j == randomCol) || (i == randomRow2 && j == randomCol2)))
{
gridArray[i][j] = '.';
}
System.out.print(gridArray[i][j]);
}
System.out.println("");
}
System.out.println("Enter a movement choice W A S or D");
do{
Scanner keyboard = new Scanner(System.in);
moveSelect = keyboard.nextLine();
if ( moveSelect.equals("w"))
{
randomRow -= 1;
validInput = true;
}
else if ( moveSelect.equals("a"))
{
randomCol -= 1;
validInput = true;
}
else if ( moveSelect.equals("s"))
{
randomRow += 1;
validInput = true;
}
else if (moveSelect.equals("d"))
{
randomCol -= 1;
validInput = true;
}
else
{
System.out.println("Invalid Entry. Try again.");
validInput = false;
}
} while (validInput == false);
gridArray[randomRow][randomCol] = 'o';
gridArray[randomRow2][randomCol2] = 'X';
for (int i = 0; i < gridArray.length; i++)
{
for (int j = 0; j < gridArray.length; j++)
{
if (!((i == randomRow && j == randomCol) || (i == randomRow2 && j == randomCol2)))
{
gridArray[i][j] = '.';
}
System.out.print(gridArray[i][j]);
}
System.out.println("");
}
Make a method to print the grid if validInput==true
public static void printGrid(char[][]gridArray){
for (int i = 0; i < gridArray.length; i++)
{
for (int j = 0; j < gridArray.length; j++)
{
System.out.print(gridArray[i][j]);
}
System.out.println("");
}
}
I modified your gridArray[randomRow][randomCol] from =' ' to ='.' because you want it to be a dot right? (If you actually want it to be a space, just leave it like it already is)
For validation, change each of the directions to things like:
if ( moveSelect.equals("w")&&randomRow!=0)
{
gridArray[randomRow][randomCol] = gridArray[randomRow-1][randomCol];
gridArray[randomRow][randomCol] = '.';
validInput = true;
}
At the end of the do,
if(validInput) printGrid(gridArray);
I'm coding a simple maze game in java. The program reads in a text "map" from an input file for the layout of the maze. The rules are simple: navigate the maze (represented by a 2D array) through user input and avoid the cave-ins (represented by Xs), and get to the 'P' (player) the the spot marked 'T'. Right now, I've got most of the code written, it's just a matter of getting it to work properly. I've set up most of the game to run with a while loop, with the boolean "got treasure" set to false. Once this rings true, it should end the game.
However, I haven't coded the circumstance in which the player actually gets the treasure though, so I'm wondering why my code simply spits out "Congratulations! You've found the treasure!" and nothing else. If anyone could shed some light on this, I'd be very grateful. My code is somewhat of a mess of loops, as our teacher has just gotten to methods, constructors, and creating our own classes. Here is the code I have so far:
import java.util.*;
import java.io.File;
public class MazeGame {
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(new File("maze.txt"));
Scanner user = new Scanner(System.in);
int rows = scan.nextInt();
int columns = scan.nextInt();
int px = 0;
int py = 0;
String [][] maze = new String[rows][columns];
String junk = scan.nextLine();
for (int i = 0; i < rows; i++){
String temp = scan.nextLine();
String[] arrayPasser = temp.split("");
for (int j = 0; j < columns; j++){
maze[i][j] = arrayPasser[i];
}
}
boolean gotTreasure = false;
while (gotTreasure = false){
for (int i = 0; i < rows; i++){
for (int j = 0; j < columns; j++){
System.out.print(maze[i][j]);
System.out.print(" ");
}
System.out.print("\n");
}
System.out.printf("\n");
System.out.println("You may:");
System.out.println("1) Move up");
System.out.println("2) Move down");
System.out.println("3) Move left");
System.out.println("4) Move right");
System.out.println("0) Quit");
int choice = user.nextInt();
int i = 0;
if (choice == 1 && i >= 0 && i < columns){
for (int k = 0; k < rows; k++){
for (int l = 0; l < columns; l++){
if (maze[k][l].equals(maze[px][py]) && maze[px][py-1].equals("X") == false){
maze[px][py] = ".";
maze[k][l-1] = "P";
maze[px][py] = maze[k][l-1];
}else if (maze[px][py-1] == "X"){
System.out.println("Cannot move into a cave-in! Try something else.");
}else {
continue;}
}
}
}
else if (choice == 2 && i >= 0 && i < columns){
for (int k = 0; k < rows; k++){
for (int l = 0; l < columns; l++){
if (maze[k][l].equals(maze[px][py]) && maze[px][py+1].equals("X") == false){
maze[px][py] = ".";
maze[k][l+1] = "P";
maze[px][py] = maze[k][l+1];
}else if (maze[px][py+1] == "X"){
System.out.println("Cannot move into a cave-in! Try something else.");
}else {
continue;}
}
}
}
else if (choice == 3 && i >= 0 && i < columns){
for (int k = 0; k < rows; k++){
for (int l = 0; l < columns; l++){
if (maze[k][l].equals(maze[px][py]) && maze[px-1][py].equals("X") == false){
maze[px][py] = ".";
maze[k-1][l] = "P";
maze[px][py] = maze[k-1][l];
}else if (maze[px-1][py] == "X"){
System.out.println("Cannot move into a cave-in! Try something else.");
}else {
continue;}
}
}
}
else if (choice == 4 && i >= 0 && i < columns){
for (int k = 0; k < rows; k++){
for (int l = 0; l < columns; l++){
if (maze[k][l].equals(maze[px][py]) && maze[px+1][py].equals("X") == false){
maze[px][py] = ".";
maze[k+1][l] = "P";
maze[px][py] = maze[k+1][l];
}else if (maze[px+1][py] == "X"){
System.out.println("Cannot move into a cave-in! Try something else.");
}else {
continue;}
}
}
}
else if (choice == 0){
System.exit(0);
}
}
System.out.println("Congratulations, you found the treasure!");
scan.close();
user.close();
}
}
And here is the sample input file:
5 5
P.XX.
.X...
...X.
XXT..
..X..
(sigh) one equals sign instead of two. You have "while (gotTreasure = false)", which assigns the value false to gotTreasure and does not enter the loop. Change it to "while (gotTreasure == false) and it enters the loop.
For future questions: please attempt to figure out on your own what is happening, and let others know what you have tried and what specific questions you have about it. It is arguable I should just have let this go, since it is essentially a request to debug your code for you. Learn to debug yourself. If trace statements aren't getting executed, it's most likely the code at that point isn't getting executed. If a loop isn't getting entered, it is almost certainly because the conditions for entering the loop don't exist.
Learn to use a debugger - eclipse (and, I am sure, lots of other development tools) has an excellent one. Find out what a breakpoint is, how to set it and examine variables when it is hit, and figure out from there what has gone wrong.
If this is a typo ignore this, if it isnt
while (gotTreasure = false) is wrong.
you are not checking if gotTreasure is false, you are assigning it false.
to check if gotTreasure is false use == operator
while(gotTreasure==false)
lemme know if this is a type, i ll delete the answer. :)
You have a simple mistake in your while loop condition,
Instead of,
while (gotTreasure = false)
You should use,
while (gotTreasure == false)
In the first case, you are assigning false to gotTreasure and in the second you are evaluating if gotTreasure is false.
I refeactored your code, because there are a lot of bad programming-styles. Now the game should run as intended.
I used a Construktor and a lot of methods, to divide your big method in small parts. -> easier to understand.
I declared attributes (known in the whole class), so that the different methods can use this variables.
You often checked for a condition like if(variable == false). Try to use if(!variable), the exclamation mark negates the value of the variable.
Your update-Methode had a lot of redundandancies.
By adding the following switch-case-Part, I could seperate the different directions:
General code for setting directions by a userinput:
switch (choice){
case 0: System.exit(0);
case 1: xdir = 0; ydir = -1; break;
case 2: xdir = 0; ydir =1; break;
case 3: xdir = -1; ydir = 0; break;
case 4: xdir = 1; ydir = 0; break;
}
Afterwards I could calculate the new position by adding xdir to x and ydir to y. This comes handy, if you try to check if the new position is in the bounds of the array.
//1. Check if the new position is in the array.
if (x+xdir >= 0 && x+xdir <columns && y+ydir >=0 && y+ydir < rows){
Here follows the whole class:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class MazeGame2 {
Scanner scan;
Scanner user;
int rows;
int columns;
String [][] maze;
int x; //Player x-Position
int y; //Player y-Position
boolean gotTreasure;
/**
* Konstruktor for the class.
*/
public MazeGame2(){
init();
game();
scan.close();
user.close();
}
/**
* Initialisation of the maze and all attributes.
*/
public void init(){
user = new Scanner(System.in); //Scanner for Userinput
/********************************
* Scanning the maze from a file.
*/
//1. Open the file. Has to be in a try-catch-Bracket, because the file might not be there.
try{
scan = new Scanner(new File("maze.txt"));
}catch(FileNotFoundException e){
e.printStackTrace();
}
//2. Scan the dimensions of the maze.
rows = scan.nextInt();
columns = scan.nextInt();
scan.nextLine(); // So that the next Line can be scanned.
maze = new String[rows][columns];//Create the maze-Array with the right dimensions.
for (int i = 0; i < rows; i++){
String temp = scan.nextLine(); //Scan one line.
for (int j = 0; j < columns; j++){
maze[i][j] = temp.substring(j, j+1);//Put every character in the maze
if (maze[i][j].equals("P")){ //Look out for the Player-Position
x = j;
y = i;
}
}
}
gotTreasure = false;
}
/**
* Prints the Input of the maze-Array. But only if the spots are visible by the player.
*/
public void printMaze(){
for (int i = 0; i < rows; i++){
for (int j = 0; j < columns; j++){
System.out.print(maze[i][j]);
System.out.print(" ");
}
System.out.println();
}
}
/**
* Prints the possebilities to move by the player.
*/
public void printUserPossebilities(){
System.out.println();
System.out.println("You may:");
System.out.println("1) Move up");
System.out.println("2) Move down");
System.out.println("3) Move left");
System.out.println("4) Move right");
System.out.println("0) Quit");
}
/**
*
*/
public void update(int choice){
int xdir=0;
int ydir=0;
// Update the direction based on the userChoice
switch (choice){
case 0: System.exit(0);
case 1: xdir = 0; ydir = -1; break;
case 2: xdir = 0; ydir =1; break;
case 3: xdir = -1; ydir = 0; break;
case 4: xdir = 1; ydir = 0; break;
}
/**
* Update the situation based on the current direction and step.
*/
//1. Check if the new position is in the array.
if (x+xdir >= 0 && x+xdir <columns && y+ydir >=0 && y+ydir < rows){
//2. Check if a step is possible
if (maze[y+ydir][x+xdir].equals("X")){
System.out.println("Cannot move into a cave-in! Try something else.");
}else{
//3. clear the P from the old Position
maze[y][x] =".";
//4. Check if the Player is over the treasure
if (maze[y+ydir][x+xdir].equals("T")){
gotTreasure = true;
}
x = x+xdir;
y = y + ydir;
maze[y][x] = "P"; //Show the new position of the player.
}
}else{
System.out.println("That's not a possible Move.");
}
}
/**
* The game-Methode that includes the game-loop and
*/
public void game(){
while (!gotTreasure){
//System.out.print('\u000C');
printMaze();
printUserPossebilities();
int userInput = user.nextInt(); //Wait for userinput
update(userInput);
}
//System.out.print('\u000C');
printMaze();
System.out.println("Congratulations, you found the treasure!");
}
public static void main(String[] args){
MazeGame2 m = new MazeGame2();
}
}