java airplane seating chart array - java

i have an issue with my 2d array its not outputting correctly, so the program is running fine, however when i choose case 4 to view airplane seating chart horizontally outputting to many x's and not in the correct spot. if any one can point me in the right direction that will be awesome!
public static void viewSeatingChartVertical(boolean seat[]){
for(int i = 0; i < 10; ++i){
for(int j = 0; j < 3; ++j){
if(seat[((j + 1) + (i * 3)) - 1])
System.out.print("x ");
else
System.out.print("o ");
}
System.out.println();
}
}
public static void viewSeatingChartHorizontal(boolean seat[]){
int [][] twoDim = new int [3][10];
int a = (twoDim.length);
int b = (twoDim[0].length);
for(int i = 0; i < a; i++){
for(int j = 0; j < b; j++) {
int x = 0;
twoDim[i][j] = x;
if(seat[((j + 1) + (i * 3)) - 1])
System.out.print("x ");
else
System.out.print("o ");
}
System.out.println();
}
}
public static void main(String args[]){
java.util.Scanner input = new java.util.Scanner(System.in);// if the system doesnt know the Scanner function it then looks to import it
boolean seating[] = new boolean[30];//declare the amount of seats available on the plane in an array
//display list of options - saving space make easier to read on smaller screen
System.out.println("Please choose an option:");
System.out.println("1 for “first class”");
System.out.println("2 for “economy”");
System.out.println("3 to view seating chart");
System.out.println("4 to view seating horizontally chart");
System.out.println("0 to exit");
System.out.print("? ");
while(true){ //loop while valid
int mOpt = input.nextInt(); //mOpt Menu Option - validate number entered, must be 0-4
switch (mOpt){
case 0: System.exit(0);
break; //system exit
case 1: // first class seats
{
System.out.print("Which seat would you like (1-9)\n");
int fcseat = input.nextInt();
if(fcseat > 0 && fcseat <10){
if(seating[fcseat - 1]){
System.out.print("That seat is taken.\n");
}
else{
seating[fcseat - 1] = true;
System.out.print("Seat number " + fcseat + " was assigned.\n");
}
}
}
break;
case 2: // economic seats
{
System.out.print("Which seat would you like (10-30)\n");
int econSeat = input.nextInt();
if(econSeat >= 10 && econSeat <= 30){ // HAD 31 NOT 30. SMH
if(seating[econSeat - 1]){
System.out.print("That seat is taken.\n");
}
else{
seating[econSeat - 1] = true;
System.out.print("Seat number " + econSeat + " was assigned.\n");
}
}
}
break;
case 3: //printout of available seats vertically
{
viewSeatingChartVertical(seating);
}
break;
case 4: //printout of available seats horizontally
{
viewSeatingChartHorizontal(seating);
}
break;
default: //wrong format or number please try again
System.out.print("Sorry, Option not recognized, please Try again.\n");
}
}
}
}

You are mixing up rows and columns on the plane with rows and columns on the screen.
Your horizontal output is really over complicated. It should be just as simple as the vertical output. The key is duplicate the code from your vertical output, but reverse the two for statements.
for(int j = 0; j < 3; ++j) {
for(int i = 0; i < 10; ++i) {
and it should magically work.
Well, almost work. This will flip the left and right sides of the plane. A small change to the first loop will fix that too. Left to student.

Related

Java lottery using arrays

I have to create a lottery game where you randomly generate six winning numbers simulating a lottery. Ask the user to enter six numbers and see if they win the lottery!
I have done a lot of it, but now im stuck. I am really new to java so forgive me. When it prompts to ask for another number it does it but it still displays it for the self-made lottery picks that display. Also, when displaying the numbers for the computer made lottery picks they are the same numbers over again that repeat and aren't 6 numbers. The counter doesn't work as well it maybe a little thing but i can't figure it out. Thank you
package arraysIntroduction;
import java.util.Scanner;
public class sizeQuestion {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
int [] user =new int [6];
int i;
//Fill user array
System.err.println("Welcome to Miwand's Lottery");
System.out.println("Please enter your 6 desiered number to enter the lottery");
System.out.println("Pick from 1 to 49");
for ( i=0;i<user.length;i++) // gets numbers until it equals 6
{
System.out.println("Number:");
user[i]= in.nextInt(); // Gets numbers from user
while (user[i] < 0 ) // if its a negative number tell user to enter again
{
System.err.println("Negative number, please enter again:");
user[i]=in.nextInt();
}
if (user[i] > 49) // if the number goes past 49 prompt again
{
System.err.println("Please enter numbers from 1 - 49");
}
}
//print out the numbers generated
for ( i=0;i < user.length; i++){
System.out.print(+user[i]+ " ");
}
System.out.println(" ");
int[] lottery = new int[6];
int guesses;
int counter=0;
int j;
int x;
{
for (j = 0; j < 6; j++) {
int randomNum = (int) (Math.random() *49 +1); // Random number created here.
for ( x = 0; x < j; x++) {
if (lottery[x] == randomNum) // Here, code checks if same random number generated before.
{
randomNum = (int) (Math.random() *49 +1);// If random number is same, another number generated.
}
lottery[j] = randomNum;
}
}
//prints out computer generated numbers
for (i = 0; i < lottery.length; i++){
for (x = 0; x< j; x++){
System.out.print(lottery[i] + " ");
if (user[i] == lottery[x] ){
counter++;
}
}
}
}
if (counter < 2){
System.out.println("Try again!");
}
if (counter == 3){
System.out.println("3 numbers matched! You won $300!");
}
if (counter == 4){
System.out.println("4 numbers matched! You won 500!");
}
if (counter == 5){
System.out.println(" 5 numbers matched! You won $1000!");
}
else if (counter == 6){
System.out.println("JACCKKKPOOOOTTTTTTT!!!!!! YOU WIN 1 MILLION DOLLARS!");
}
}
}
I saw multiple problems in your program.
First, the printout problem can be solved by moving the print statement from inner loop to outer loop
for (i = 0; i < lottery.length; i++) {
System.out.print(lottery[i] + " ");
for (x = 0; x < j; x++) {
if (user[i] == lottery[x]) {
counter++;
}
}
}
Also, you are not assigning the first random number correctly and it is always using the default, which is 0
Solution:
for (j = 0; j < 6; j++) {
int randomNum = (int) (Math.random() * 49 + 1); // Random number created here.
for (x = 0; x < j; x++) {
if (lottery[x] == randomNum) // Here, code checks if same random number generated before.
{
randomNum = (int) (Math.random() * 49 + 1);// If random number is same, another number generated.
}
}
lottery[j] = randomNum;
}
Plus, you didn't check if counter is equal to 2
Solution:
if (counter <= 2) {
System.out.println("Try again!");
}
And, the logic in "If random number is same, another number generated." may not be correct, since it may generate the same number again. You need a while loop to generate a new number until it is not equal to any of the generated numbers.
Another thing about coding style is that for any "for loops"
This :
int i=0;
for (i = 0; i < length; i++)
Should be replaced by this:
for (int i = 0; i < length; i++)
As I already said in the comments, you should move the print statement from the inner loop to the outer loop.
Your code should look like this:
for (i = 0; i < lottery.length; i++) { // outer loop
System.out.print(lottery[i] + " ");
for (x = 0; x < j; x++) { // inner loop
if (user[i] == lottery[x]) {
counter++;
}
}
}

Building a base for my christmas tree

I'm trying to build a Christmas tree with a user inputted triangular top and a rectangular base, but I'm currently stuck while building the base. The specifications are as follows: The triangle starts with a single * and increases the amount of * on each row by a total of 2 per line, such that the final row is 2(n)-1 with n being the inputted height of the triangle. The height of the rectangle (stump) underneath the tree is equal to 1 plus (1/5)n and the width of the stump is 1/3n however if the result of 1/3n is an even integer, add 1 to the total stump width. (i.e the stump width is always an odd number.)
Here's what i have so far, the triangular part of the tree is fine, but the rectangle is a mess.
public class xmasTree {
public static final int TREE_MAXIMUM = 20;
public static final int TREE_MINIMUM = 3;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
//User introduction
System.out.println("This program prints a \"Christmas\" tree. You "
+ "choose how big the tree will be (within reason);
// prompt for and get user input
System.out.println("How tall should the top of the tree be?");
int treeHeight = keyboard.nextInt();
while (treeHeight < TREE_MINIMUM || TREE_MAXIMUM < treeHeight) {
System.out.println("That's not a valid size. I can only do trees "
+ "from 3 to 20.");
System.out.println("Qutting now.");
System.exit(0);
}
//Print the top triangle section of the christmas tree
for (int i = 0; i < treeHeight; i++) {
for (int j = 0; j < treeHeight - i; j++) {
System.out.print(" ");
}
for (int k = 0; k < (2 * i + 1); k++) {
System.out.print("*");
}
System.out.println();
}
//Print the bottom rectangle section of the tree
for (int c = 0; c <= (1 + (treeHeight / 5)); c++) {
for (int d = 0; d <= (treeHeight / 3); d++) {
System.out.print("");
}
System.out.printf("*");
}
}
}
If anyone could help me figure out how to get the proper input shape for the rectangle that would be awesome, I know I can center it with a simple printf once it is built properly.
First, you need to visualize what your result should be.
Example, n = 8, so base should be 1 + n/5 = 2 tall and n / 3 = 2 adjusted to 3 wide.
*
***
*****
*******
*********
***********
*************
***************
***
***
Your code has the following problems:
print("") is a meaningless statement. It does nothing.
You don't print any leading spaces for indentation.
You don't print * for a count equal to base width.
You don't call println() so base height will definitely not work.
You got the tree part good, so you really shouldn't have problems with this. I won't give you the answer, but hopefully this visual example will help you do it yourself.
And if you make your for loop start at 0, then don't use a equal sign, as it will work 1 more time to what you expect
You almost made it, just a couple comments about your code:
In the last for you should have used < instead of <= like you did on the beggining
You had clear the rules so you just needed to write them in your code, like I did in my code try to make it more clear, find the height and the width of the stump before writing it out
In the inner for you should have printed out the * and in the outer for you just needed to print a new line
Scanner keyboard = new Scanner(System.in);
//User introduction
System.out.println("This program prints a \"Christmas\" tree. You "
+ "choose how big the tree will be (within reason)");
// prompt for and get user input
System.out.println("How tall should the top of the tree be?");
int treeHeight = keyboard.nextInt();
while (treeHeight < TREE_MINIMUM || TREE_MAXIMUM < treeHeight) {
System.out.println("That's not a valid size. I can only do trees "
+ "from 3 to 20.");
System.out.println("Qutting now.");
System.exit(0);
}
//Print the top triangle section of the christmas tree
for (int i = 0; i < treeHeight; i++) {
for (int j = 0; j < treeHeight - i; j++) {
System.out.print(" ");
}
for (int k = 0; k < (2 * i + 1); k++) {
System.out.print("*");
}
System.out.println();
}
//Print the bottom rectangle section of the tree
int stumpHeight = (1 + (treeHeight / 5));
int stumpWidth;
if ((treeHeight / 3) % 2 == 0) {
//it is even add 1
stumpWidth = (treeHeight / 3) + 1;
} else {
//it is odd keep it like that
stumpWidth = (treeHeight / 3);
}
for (int c = 0; c < stumpHeight; c++) {
//sorry for adding the spaces but I don't like the incomplete answers
//centering
for (int d = 0; d < treeHeight - stumpWidth/2; d++) {
System.out.print(" ");
}
//adding stump
for (int d = 0; d < stumpWidth; d++) {
System.out.print("*");
}
//going to the next line
System.out.println();
}

How to create a Battleship Warship game algorithm

I'm having trouble randomizing and adding a 2x2 ship into the game board. I need it to look like the following:
currently I can only seem to get a 1x1 ship and don't quite understand the logic for adding the 2x2 and randomizing it so that they're all connected.
also when the user inputs a '2' at the main menu I need to show the solution, meaning where the ships are. Which I also could use some help on.
Not nearly finished but please be critical when it comes to judging my code, everything helps!
Thanks in advance.
import java.util.Scanner;
public class Battleship
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int [][] board = new int [5][5];
int [][] ship = new int [4][2];
int [] shot = new int[2];
boolean done = false;
resetboard(board);
while(!done)
{
displayBoard(board);
displayMenu();
for(int ships=0 ; ships < 4 ; ships++)
{
ship[ships][0]=(int) Math.random() * 5 + 1;
ship[ships][1]=(int) Math.random() * 5 + 1;
}
int choice = getMenuInput(input);
if(choice == 1)
{
getRow(shot);
getColumn(shot);
if(fireShot(shot,ship) == true)
{
board[shot[0]][shot[1]]= 1;
}
else
{
board[shot[0]][shot[1]]= 0;
}
}
else if(choice == 2)
{
for (int x = 0; x < 5; x++)
{
for(int y = 0; y < 5; y++)
{
for(int z = 0; z < 3; z++)
{
if(board[x][y] == ship[z][0] && board[x][y] == ship[z][1] )
{
board[ship[z][0]][ship[z][1]]= 1;
}
}
}
}
displayBoard(board);
}
else if (choice == 3)
{
done = true;
System.out.println("Thanks For Playing");
}
}
}
public static void displayBoard(int [][] board)
{
System.out.println(" A B C D E");
for(int r =0; r < 5; r++)
{
System.out.print((r + 1) + "");
for(int c = 0; c < 5; c++)
{
if(board[r][c] == -1)
{
System.out.print(" -");
}
else if(board[r][c] == 0)
{
System.out.print(" X");
}
else if(board[r][c] == 1)
{
System.out.print(" *");
}
}
System.out.println("");
}
}
public static void resetboard(int[][] a)
{
for(int row=0 ; row < 5 ; row++ )
{
for(int column=0 ; column < 5 ; column++ )
{
a[row][column]=-1;
}
}
}
public static void displayMenu()
{
System.out.println("\nMenu:");
System.out.println("1. Fire Shot");
System.out.println("2. Show Solution");
System.out.println("3. Quit");
}
public static int getMenuInput(Scanner input)
{
int in = 0;
if(input.hasNextInt())
{
in = input.nextInt();
if(in>0 && in<4)
{
in = in;
}
else
{
System.out.println("Invalid Entry, Please Try Again.\n");
}
}
else
{
System.out.println("Invalid Entry, Please Try Again.\n");
input.nextInt();
}
return in;
}
public static void getRow(int [] shot)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a Row Number: ");
shot[0] = shotValid(input);
shot[0]--;
}
public static void getColumn(int [] shot)
{
Scanner input = new Scanner(System.in);
int numb = 0;
System.out.println("Enter a Column Letter: ");
String choice = input.next();
if (choice.equals("A"))
{
numb = 0;
}
else if(choice.equals("B"))
{
numb = 1;
}
else if( choice.equals("C"))
{
numb = 2;
}
else if(choice.equals("D"))
{
numb = 3;
}
else if(choice.equals("E"))
{
numb = 4;
}
else
{
System.out.println("2Invalid Entry, Please Try Again.\n");
input.nextLine();
}
shot[1] = numb;
}
public static boolean fireShot(int [] shot, int [][]ship)
{
boolean result = false;
for(int shipHit=0 ; shipHit<ship.length ; shipHit++)
{
if( shot[0]==ship[shipHit][0] && shot[1]==ship[shipHit][1])
{
result = true;
}else
{
result = false;
}
}
return result;
}
public static int shotValid(Scanner quantity)
{
int shot = 0;
boolean done = false;
while(!done)
{
if(quantity.hasNextInt())
{
shot = quantity.nextInt();
if(shot>0 && shot<6)
{
shot = shot;
done = true;
}
else
{
System.out.println("1Invalid Entry, Please Try Again.\n");
}
}
else
{
System.out.println("2Invalid Entry, Please Try Again.\n");
quantity.next();
}
}
return shot;
}
}
You want to place a single ship of size 2×2 on the board and do this:
for(int ships=0 ; ships < 4 ; ships++)
{
ship[ships][0]=(int) Math.random() * 5 + 1;
ship[ships][1]=(int) Math.random() * 5 + 1;
}
There are several errors here:
The random variables will always be 1, because the (int) conversion affects only the result of Math.random(), which is a pseudo-random floating-point number between 0 and 1 exclusively. Conversion to int truncates this to 0. Use (int) (Math.Random() * 5), which will yield a random number from 0 to 4.
You shouldn't add 1. Internally, your game uses the zero-base indices that Java uses, which is good. ()These are known to the outside as rows 1 to 5 ande columns A to E, but you take care of that in your getRow and getColumn functions.)
You place up to four independent ships of size 1×1. (This is up to four, because you might end up wit one ship in an already occupied place.)
To place a single 2×2 ship, just determine the top left corner randomply and make the other ship coordinates dependent on that:
int x = (Math.random() * 4);
int y = (Math.random() * 4);
ship[0][0] = x;
ship[0][1] = y;
ship[1][0] = x + 1;
ship[1][1] = y;
ship[2][0] = x;
ship[2][1] = y + 1;
ship[3][0] = x + 1;
ship[3][1] = y + 1;
You now have two separate data structures: The board, which is all minus ones initially, and the list of ships. Your display routine suggests that you want three different values for a cell in the board: −1 is water; 1 is an unarmed part of a ship and 0 is where a shot has been fired.
But you never set these values. You set the position of the ship before displaying, but you should probably set them straight away. You should also set the locations of shots, so that you never fire at the same cell.
You need two modes for displaying the board: The in-play mode, where the unharmed ships are displayed as water and the solution mode, which shows everything as it is. You could so this by passing a flag to the routine.
Now if you think about it, you don't really need the ship array. Just use the information in the board:
int x = (Math.random() * 4);
int y = (Math.random() * 4);
board[x][y] = 1;
board[x + 1][y] = 1;
board[x][y + 1] = 1;
board[x + 1][y + 1] = 1;
Keep a count of ships, initially 4. When you fire at water, mark the cell with 0. When you fire at a ship, mark the cell as 0 and decrement the count of ships. If the count of ships is zero, the player has won. Otherwise, redisplay the boatrd and shoot again.

My clues in my game are off (java)

My brother offered me a challege to help my studies by making a game that only runs in the main method instead of using other classes to make sure I still remember my old stuff. Bases off that I went with a cat and mouse game where the player is the mouse looking for the cheese while avoiding all the cats. When you enter an empty "room" (cell) the game is supposed to give you a clue at how far you are from the cheese. Now the game runs but my clues just keep going higher and higher to the point where it over the amount of rooms in the maze. I am stumpped on where the problem is.
Here's the code
import java.util.Scanner;
import java.util.Random;
public class CatAndMouse
{
public static final int MAX = 10;
public static void main(String args[ ])
{
Scanner mouse = new Scanner(System.in);
Random placement = new Random();
boolean check = true, gameOver = false, win = false, lose = false;
final int row = MAX;
final int col = MAX;
final int page = MAX;
int cheeseX, cheeseY, cheeseZ;
int cheese = 1;
int catX, catY, catZ;
int cat = 2;
int mouseRow;
int mouseCol;
int mousePage;
int mouseMove;
int empty = 0;
int clue = 0;
int clueCount = 0;
int winQuotes;
int loseQuotes;
int [][][]maze = new int [row][col][page];
for(int i = 0; i < MAX; i++)
{
for(int j = 0; j < MAX; j++)
{
for(int k = 0; k < MAX; k++)
{
maze[i][j][k] = empty;
}//page
}//col
}//row
cheeseX = placement.nextInt(row);
cheeseY = placement.nextInt(col);
cheeseZ = placement.nextInt(page);
maze[cheeseX][cheeseY][cheeseZ] = cheese;
for (int i = 0; i < 500; i++)
{
catX = placement.nextInt(row);
catY = placement.nextInt(col);
catZ = placement.nextInt(page);
maze[catX][catY][catZ] = cat;
if ((maze[catX][catY][catZ]) == (maze[cheeseX][cheeseY][cheeseZ]))
{
catX = placement.nextInt(row);
catY = placement.nextInt(col);
catZ = placement.nextInt(page);
maze[catX][catY][catZ] = cat;
}//if place with cheese
}//cat placement loop
System.out.println("Hello there, my name is Q, do you like it? it's short for Q. So you're probably asking yourself \"why am I now a mouse?\"");
System.out.println("The answer is simple, I was bored and you humans are so much fun to play with, but don't worry I can change you back.");
System.out.println("All you have to do is win my little game and you'll be back to your old self again, loose and...well just don't lose.");
System.out.println("In this maze there is a piece of cheese, find it and you win. But be careful now, I added a \'few\' cats to hunt you.");
System.out.println("Can't make this too easy now can we? But don't worry, you'll be given clues if you're close to the cheese or not");
System.out.println("The maze itself is 10*10*10 and to move through it enter an integer between 0-9.");
System.out.println("Now then, let the game begin.");
System.out.println();
do
{
System.out.print("Enter row: ");
mouseRow = mouse.nextInt();
if((mouseRow < 0) || (mouseRow > 9))
{
while (check == true)
{
System.out.print("I said, it needs to be an integer between 0-9. Try again: ");
mouseRow = mouse.nextInt();
if((mouseRow >= 0) && (mouseRow <= 9))
check = false;
}//while closer
}//row check
check = true;
System.out.print("Enter column: ");
mouseCol = mouse.nextInt();
if((mouseCol < 0) || (mouseCol > 9))
{
while (check == true)
{
System.out.print("I said, it needs to be an integer between 0-9. Try again: ");
mouseCol = mouse.nextInt();
if((mouseCol >= 0) && (mouseCol <= 9))
check = false;
}//while closer
}//column check
check = true;
System.out.print("Enter page: ");
mousePage = mouse.nextInt();
if((mousePage < 0) || (mousePage > 9))
{
while (check == true)
{
System.out.print("I said, it needs to be an integer between 0-9. Try again: ");
mousePage = mouse.nextInt();
if((mousePage >= 0) && (mousePage <= 9))
check = false;
}//while closer
}//page check
check = true;
mouseMove = maze[mouseRow][mouseCol][mousePage];
System.out.println();
/*================[Win/Lose]===============*/
if (mouseMove == 2)
{
gameOver = true;
lose = true;
}//loser
if (mouseMove == 1)
{
gameOver = true;
win = true;
}//winner
/*===============[Win/Lose]===============*/
/*=================[Clue]=================*/
if(mouseRow == cheeseX)
{
System.out.println("In same row as cheese!");
}//if same row
else if (mouseRow > cheeseX)
{
for(int i = cheeseX; i <= mouseRow; i++)
{
clueCount++;
}//for loop closer
}//if mouse is larger
else
{
for(int i = mouseRow; i <= cheeseX; i++)
{
clueCount++;
}//for loop closer
}//else cheese is larger
clue = clue + clueCount;
if(mouseCol == cheeseY)
{
System.out.println("In same column as cheese!");
}//if same colum
if (mouseCol > cheeseY)
{
for(int i = cheeseY; i <= mouseCol; i++)
{
clueCount++;
}//for loop closer
}//if mouse is larger
else
{
for(int i = mouseCol; i <= cheeseY; i++)
{
clueCount++;
}//for loop closer
}//else cheese is larger
clue = clue + clueCount;
if(mousePage == cheeseZ)
{
System.out.println("In same page as cheese!");
}//if same page
if (mousePage > cheeseZ)
{
for(int i = cheeseZ; i <= mousePage; i++)
{
clueCount++;
}//for loop closer
}//if mouse is larger
else
{
for(int i = mousePage; i <= cheeseZ; i++)
{
clueCount++;
}//for loop closer
}//else cheese is larger
clue = clue + clueCount;
System.out.println("You are " + clue + " cells away from the cheese.");
System.out.println();
/*=================[Clue]=================*/
}while (gameOver == false);
if (win == true)
{
winQuotes = (int)(3 * Math.random()) + 1;
switch (winQuotes)
{
case 1:
System.out.println("You found the cheese! Now it's time to send you back, but don't worry. I'm sure we'll meet again soon.");
break;
case 2:
System.out.println("An excellent job, maybe you were meant to be a mouse all long. What, change you back? Oh fine.");
break;
default:
System.out.println("Congradulation, I don't think Captian Picard couldn't have done it better. Maybe I should pay him a visit.");
break;
}//win switch
}//if you won
if (lose == true)
{
loseQuotes = (int)(3 * Math.random()) + 1;
switch(loseQuotes)
{
case 1:
System.out.println("Well at least you fed a hungry cat right? Star Fleet would be so proud to have you on one of their ships.");
break;
case 2:
System.out.println("Oh come on, don't tell me you wore a red shirt before I brought you here.");
break;
default:
System.out.println("Maybe I should have brought Captian Janeway here instead, I still owe her for that punch to my face.");
break;
}//lose switch
}//if you lose
}//main closer
} //class closer
You never reinitialize your clue variable to 0 in your do/while loop. So, everytime you run through the loop, instead of setting clue to the current clue value, you keep adding to it (clue = clue + clueCount).
You aren't resetting clue to zero in the big do-while loop
So it's seems logical to me that the clues can't do anything but go higher, because it keep adding the new count to itself (clue = clue + clueCount)

Java: Programming a simple maze game

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();
}
}

Categories