This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
I want to create a game called Crap. The problem that I am facing is that the main while loop does not end despite the condition being set to false (by user inputing "no" when asked if they want to conitnue playing). What is the problem here? Comments are inserted where I think the problem is.
import java.util.Scanner;
public class crap {
public static void main(String[] args) {
System.out.println("You are about to play the game of Crap. Press Enter to continue.");
Scanner enter = new Scanner (System.in);
String hitEnter = enter.nextLine();
Scanner input = new Scanner(System.in);
String proceed = "yes";
// This loop does not exit even if proceed == "no"
while (proceed != "no"){
int playerPoint;
int firstDice = 1 + (int) (Math.random() * 10) % 6;
int secondDice = 1 + (int) (Math.random() * 10) % 6;
int throwSum = firstDice + secondDice;
if (throwSum == 7 || throwSum == 11) {
System.out.println("Congratulations! You win on your first roll! You rolled "
+ firstDice + " and " + secondDice + " for a total of " + throwSum);
}
else if (throwSum == 2 || throwSum == 3 || throwSum == 12) {
System.out.println("Sorry, you crapped out, you lose! You rolled " + firstDice +
" and " + secondDice + " for a total of " + throwSum);
} else {
playerPoint = throwSum;
System.out.println("You rolled " + firstDice + " + " + secondDice + " which is "
+ playerPoint);
System.out.println("Your point is " + playerPoint + " now. Good luck.");
while (throwSum != 7 ) {
firstDice = 1 + (int) (Math.random() * 10) % 6;
secondDice = 1 + (int) (Math.random() * 10) % 6;
throwSum = firstDice + secondDice;
if (throwSum != 7) {
System.out.println("You rolled " + firstDice + " + " + secondDice +
" which is " + throwSum);
if (throwSum == playerPoint) {
System.out.println("Congratulations! You win. You reached your point.");
break;
}
System.out.println("Your point is " + playerPoint + ". Good luck.");
}
else {
System.out.println("You rolled " + firstDice + " + " + secondDice +
" which is " + throwSum);
System.out.println("Sorry, you crapped out, you lose.");
System.out.println("You rolled 7 before reaching your point.");
break;
}
}
}
System.out.println("Do you want to play again? yes/no: ");
// even if user enters "no" the loop does not exit
proceed = input.nextLine();
}
System.out.println("Thanks for playing.");
enter.close();
input.close();
}
}
You are using the wrong operator. != checks if the two objects on left and right side are the the same (e.g. two variables reference the same object in memory).
You must write while (! "no".equals(proceed) ).
I did not write while (! proceed.equals("no") ) on purpose because if the string is null then you would get a NullPointerException.
I am not sure if Scanner.readLine() does ever return a null string, so it may make no difference here. But writing it in the "reverse" way as in my first example is more safely in general.
For a String, the == operator is used to comparing the reference of the given strings, depending on if they are referring to the same objects. When you compare two strings using == operator, it will return true if the string variables are pointing toward the same java object. Otherwise, it will return false .
You have to use .equals(String) to compare Strings, like so:
import java.util.Scanner;
public class crap {
public static void main(String[] args) {
System.out.println("You are about to play the game of Crap. Press Enter to continue.");
Scanner enter = new Scanner (System.in);
String hitEnter = enter.nextLine();
Scanner input = new Scanner(System.in);
String proceed = "yes";
// This loop does not exit even if proceed == "no"
while (!proceed.equals("no")){
int playerPoint;
int firstDice = 1 + (int) (Math.random() * 10) % 6;
int secondDice = 1 + (int) (Math.random() * 10) % 6;
int throwSum = firstDice + secondDice;
if (throwSum == 7 || throwSum == 11) {
System.out.println("Congratulations! You win on your first roll! You rolled "
+ firstDice + " and " + secondDice + " for a total of " + throwSum);
}
else if (throwSum == 2 || throwSum == 3 || throwSum == 12) {
System.out.println("Sorry, you crapped out, you lose! You rolled " + firstDice +
" and " + secondDice + " for a total of " + throwSum);
} else {
playerPoint = throwSum;
System.out.println("You rolled " + firstDice + " + " + secondDice + " which is "
+ playerPoint);
System.out.println("Your point is " + playerPoint + " now. Good luck.");
while (throwSum != 7 ) {
firstDice = 1 + (int) (Math.random() * 10) % 6;
secondDice = 1 + (int) (Math.random() * 10) % 6;
throwSum = firstDice + secondDice;
if (throwSum != 7) {
System.out.println("You rolled " + firstDice + " + " + secondDice +
" which is " + throwSum);
if (throwSum == playerPoint) {
System.out.println("Congratulations! You win. You reached your point.");
break;
}
System.out.println("Your point is " + playerPoint + ". Good luck.");
}
else {
System.out.println("You rolled " + firstDice + " + " + secondDice +
" which is " + throwSum);
System.out.println("Sorry, you crapped out, you lose.");
System.out.println("You rolled 7 before reaching your point.");
break;
}
}
}
System.out.println("Do you want to play again? yes/no: ");
// even if user enters "no" the loop does not exit
proceed = input.nextLine();
}
System.out.println("Thanks for playing.");
enter.close();
input.close();
}
}
Related
I am stuck at a part where in a game, I use while loop and to end the loop and get the results of the game, I want either "player1" or "player2" to enter "Q", and so i tried doing it like this:
if (player1.equals("Q") || player2.equals("Q")){
go = false; //go is a boolean variable
}
This doesn't seem to work as I have to enter "Q" for both player1 and player2 for the game to end, but instead I just want either of them to enter "Q" and the game would stop.
Code:
import java.util.Scanner;
public class Team {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Soccer Game Between 2 Teams");
System.out.println("Win is 2 points" + "\n" + "Loss is worth 0 points" + "\n" + "Overtime is worth 1 point");
System.out.println("Type W, O, or L" + "\n" + "Type Q to end the game");
int pointsw = 0;
int pointsl = 0;
int pointso = 0;
int pointsw2 = 0;
int pointsl2 = 0;
int pointso2 = 0;
int totalpoints = 0;
int totalpoints2 = 0;
int counter = 0;
int counter2 = 0;
boolean go = true;
System.out.println("\n" + "Enter team one:");
String phrase = keyboard.next();
System.out.println("\n" + "Enter team two:");
String phrase2 = keyboard.next();
System.out.println();
while (go) {
System.out.println("Enter " + phrase + " Result:");
String team1 = keyboard.next();
System.out.println("Enter " + phrase2 + " Result");
String team2 = keyboard.next();
if (team1.equals("W") || team1.equals("w")) {
pointsw += 2;
} else if (team1.equals("O") || team1.equals("o")) {
pointso += 1;
} else if (team1.equals("L") || team1.equals("l")) {
pointsl += 0;
}
counter++;
if (team2.equals("W") || team2.equals("w")) {
pointsw2 += 2;
} else if (team2.equals("O") || team2.equals("o")) {
pointso2 += 1;
} else if (team2.equals("L") || team2.equals("l")) {
pointsl2 += 0;
}
counter2++;
totalpoints = pointsw + pointso + pointsl;
totalpoints2 = pointsw2 + pointso2 + pointsl2;
if (team1.equals("Q") || team2.equals("Q")) {
go = false;
if (totalpoints > totalpoints2) {
System.out.println(phrase + " wins with " + totalpoints + " points");
System.out.println("It took " + phrase + " " + counter + " rounds to win");
} else if (totalpoints < totalpoints2) {
System.out.println(phrase2 + " wins with " + totalpoints2 + " points");
System.out.println("It took " + phrase2 + " " + counter2 + " rounds to win");
} else if (totalpoints == totalpoints2) {
int totalrounds = counter + counter2;
System.out.println("It is tie game between " + phrase + " and " + phrase2);
System.out.println("The game lasted till " + totalrounds + " rounds");
}
}
}
}
}
You should reorganize your code:
while (true) {
System.out.println("Enter " + phrase + " Result:");
String team1 = keyboard.next().toLowerCase();
if ("q".equals(team1)) {
break;
}
System.out.println("Enter " + phrase2 + " Result");
String team2 = keyboard.next().toLowerCase();
if ("q".equals(team2)) {
break;
}
if (team1.equals("w")) {
pointsw += 2;
} else if (team1.equals("o")) {
pointso += 1;
} else if (team1.equals("l")) {
pointsl += 0;
}
counter++;
if (team2.equals("w")) {
pointsw2 += 2;
} else if (team2.equals("o")) {
pointso2 += 1;
} else if (team2.equals("l")) {
pointsl2 += 0;
}
counter2++;
totalpoints = pointsw + pointso + pointsl;
totalpoints2 = pointsw2 + pointso2 + pointsl2;
} // loop completed
if (totalpoints > totalpoints2) {
System.out.println(phrase + " wins with " + totalpoints + " points");
System.out.println("It took " + phrase + " " + counter + " rounds to win");
} else if (totalpoints < totalpoints2) {
System.out.println(phrase2 + " wins with " + totalpoints2 + " points");
System.out.println("It took " + phrase2 + " " + counter2 + " rounds to win");
} else if (totalpoints == totalpoints2) {
int totalrounds = counter + counter2;
System.out.println("It is tie game between " + phrase + " and " + phrase2);
System.out.println("The game lasted till " + totalrounds + " rounds");
}
I'm not completely sure, but I think the issue is that after player 1 / player 2 says 'Q'
the scanner is still waiting for the next line to read.
String phrase = keyboard.next();
System.out.println("\n"+"Enter team two:");
String phrase2 = keyboard.next();//if player 1 types q this next() method must be resolved before it will continue to the logic
so add an if statement before play 2 goes asking if player 1 typed 'Q' , if so calculate scores and end game, if player 1 did not type 'Q' use else statement to continue on to player 2's turn
// I've been working on this all day but still seem to be stuck.
// I'm not getting any obvious errors but the looping seems to be broken.
// I'm a beginner so its very likely I missed something big but just overlooked it.
// This assignment is due at midnight for my class lol.
// I feel like I constructed the base format decently however my unfamiliarity with using loops is really throwing me for one. I've looked online elsewhere but many of the "dice" programs people have made only pertain to one 6-sided die and do not involve a turn based user input.
// Any useful tips would be fantastic, is there a more efficient way to go about constructing this game? I know creating multiple classes would have cleaned up the look of the program but I'm really only looking for functionality at the moment.
package prgm06;
import java.util.Scanner;
public class DiceGame
{
public static void main(String []args) //main DiceGame loop.
{
String answer;
Scanner stdIn = new Scanner(System.in);
int userWin = 0, userLose = 0, turnCounter = 0;
System.out.println("\t" + "Welcome to Computer Dice");
System.out.println("-----------------------------------------");
System.out.println("The outcome of your roll will determine" + "\n" + "if you win or lose the round." + "\n");
System.out.println("Any Quad and you win.");
System.out.println("Any Triple and you win.");
System.out.println("Any High Pair and you win.");
System.out.println("Anything else and you lose.");
System.out.println("-----------------------------------------");
System.out.println("Do you wish to play? [y,n]: ");
do { // I always want the dice to roll unless "n" is selected.
answer = stdIn.next();
int d1 = (int)(Math.random() * 4) + 1;
int d2 = (int)(Math.random() * 4) + 1;
int d3 = (int)(Math.random() * 4) + 1;
int d4 = (int)(Math.random() * 4) + 1;
}
while(answer.equalsIgnoreCase("y")); // issues with "y" not printing if/ else statements
{
int d1 = (int)(Math.random() * 4) + 1;
int d2 = (int)(Math.random() * 4) + 1;
int d3 = (int)(Math.random() * 4) + 1;
int d4 = (int)(Math.random() * 4) + 1;
System.out.println(d1 + "\t" + d2 + "\t" + d3 + "\t" + d4);
if ((d1 == d2) && (d1 == d3) && (d1 == d4))
{
userWin++;
System.out.println("\n" + "Round Results: Win");
System.out.println(turnCounter + " Rounds played.");
}
else
{
userLose++;
System.out.println("\n" + "Round Results: Loss");
System.out.println(turnCounter + " Rounds played.");
}
}
// do
{
answer = stdIn.next(); // I'm not sure if i need to keep using this at each segment
}
for(answer.equalsIgnoreCase("n");; // will not print on first user input of "n".
{
// System.out.println();
System.out.println("Game Results:");
System.out.println("User won: " + userWin + " Games.");
System.out.println("User lost: " + userLose + " Games.");
if (userWin > userLose)
{
System.out.println("Your win/loss ratio is: " + (userWin/userLose) + " Good Job!");
System.out.println(turnCounter + " Rounds played.");
}
else if (userWin < userLose)
{
System.out.println("Your win/loss ratio is: " + (userWin/userLose) + " You shouldn't bet money on this game...");
System.out.println(turnCounter + " Rounds played.");
}
else
{
System.out.println("Your win/loss ratio is: 1.0 .");
System.out.println(turnCounter + " Rounds played.");
}
break;
}
}
}
I've edited your code. Some errors were related to syntax, and some were possibly related to the logical flows. This should work as a base, and you can modify and improve it as you see fit:
import java.util.Scanner;
public class DiceGame {
public static void main(String []args) //main DiceGame loop.
{
String answer;
Scanner stdIn = new Scanner(System.in);
int userWin = 0, userLose = 0, turnCounter = 0;
System.out.println("\t" + "Welcome to Computer Dice");
System.out.println("-----------------------------------------");
System.out.println("The outcome of your roll will determine" + "\n" + "if you win or lose the round." + "\n");
System.out.println("Any Quad and you win.");
System.out.println("Any Triple and you win.");
System.out.println("Any High Pair and you win.");
System.out.println("Anything else and you lose.");
System.out.println("-----------------------------------------");
do { // I always want the dice to roll unless "n" is selected.
System.out.println();
System.out.println("Do you wish to play? [y,n]: ");
answer = stdIn.next();
if (answer.equalsIgnoreCase("y")) {
turnCounter++;
int d1 = (int)(Math.random() * 4) + 1;
int d2 = (int)(Math.random() * 4) + 1;
int d3 = (int)(Math.random() * 4) + 1;
int d4 = (int)(Math.random() * 4) + 1;
System.out.println(d1 + "\t" + d2 + "\t" + d3 + "\t" + d4);
if ((d1 == d2) || (d1 == d3) || (d1 == d4) || (d2 == d3) || (d2 == d4) || (d3 == d4) {
userWin++;
System.out.println("\n" + "Round Results: Win");
System.out.println(turnCounter + " Rounds played.");
} else {
userLose++;
System.out.println("\n" + "Round Results: Loss");
System.out.println(turnCounter + " Rounds played.");
}
System.out.println("Game Results:");
System.out.println("User won: " + userWin + " Games.");
System.out.println("User lost: " + userLose + " Games.");
System.out.println("Your win/loss ratio is: " + userWin + ":" + userLose);
if (userWin > userLose) {System.out.println("Good Job!");}
if (userWin < userLose) {System.out.println("You shouldn't bet money on this game...");}
System.out.println(turnCounter + " Rounds played.");
}
} while(answer.equalsIgnoreCase("y"));
}
}
Some points to note:
The game will keep running as long as the user types in 'y', since that is your condition: answer.equalsIgnoreCase("y").
I changed the win condition logic to check for at least a pair using the logical OR operator
I removed the division operator for the ratio result for win/loss and just replaced it with a display of wins:losses; This could be changed if you want it to calculate for an actual percentage or decimal value, but you have to check for cases where losses == 0 to prevent a divide by zero error
The Do-While loop should encompass all of the gameplay from start to finish, so the question that asks you to play again should go at the start or at the end of this loop (I placed it at the start)
int i = 1;
int answer;
int d;
int e;
boolean alive = true;
System.out.println("\n");
System.out.println(enemies[i].getName() + " has appeared!");
System.out.print("\n");
while (alive == true) {
System.out.println("Hitpoints[HP]: " + enemies[i].getHP());
System.out.println("Attack[ATK] : " + enemies[i].getATK());
System.out.println("Mana[MANA] : " + enemies[i].getMANA());
System.out.println("\n");
System.out.println("[1 - Attack]");
System.out.println("[2 - Flee]");
answer = In.getInt();
System.out.println("\n");
if (answer == 1) {
if (user.getP_HP() > 0) {
d = enemies[i].getHP() - user.getP_ATK();
enemies[i].setHP(d);
System.out.println(user.getP_Name() + " strikes the " + enemies[i].getName() + " for " + user.getP_ATK() + " damage.");
System.out.println(enemies[i].getName() + " has " + enemies[i].getHP() + " HP remaining.");
System.out.println("\n");
} else if (user.getP_HP() <= 0) {
System.out.println(user.getP_Name() + " has been slain by the " + enemies[i].getName() + "!");
alive = false;
}
if (enemies[i].getHP() > 0) {
e = user.getP_HP() - enemies[i].getATK();
user.setP_HP(e);
System.out.println("The " + enemies[i].getName() + " attacked you for " + enemies[i].getATK() + " damage.");
System.out.println(user.getP_Name() + " has " + user.getP_HP() + " HP remaining.");
System.out.println("\n");
} else if (enemies[1].getHP() <= 0) {
System.out.println(user.getP_Name() + " has slain the " + enemies[i].getName() + "!");
alive = false;
}
} else if (answer == 2) {
System.out.println("You try to run, but fall into a pit of spikes and die!");
alive = false;
}
}
Hello, I'm having problems solving this issue for about 2 hours now. What I want to do is for the enemy to die immediately after its HP reaches 0 or below, and same for the player.
This works only if the player kills the goblin first, and not vice versa.
Whenever the enemy kills the player first, it does not output that you have been killed. Instead, it gives you the option to choose if you want to attack or flee again. After choosing the attack option, it only then states that you have been killed. That's not all though, after that the goblin attacks you again before the program stops.
Here is the sample output if the enemy kills you first:
stackoverflow strikes the Goblin for 1 damage.
Goblin has 12 HP remaining.
The Goblin attacked you for 3 damage.
stackoverflow has 1 HP remaining.
Hitpoints[HP]: 12
Attack[ATK] : 3
Mana[MANA] : 1
[1 - Attack]
[2 - Flee]
1
stackoverflow strikes the Goblin for 1 damage.
Goblin has 11 HP remaining.
The Goblin attacked you for 3 damage.
stackoverflow has -2 HP remaining.
Hitpoints[HP]: 11
Attack[ATK] : 3
Mana[MANA] : 1
[1 - Attack]
[2 - Flee]
1
stackoverflow has been slain by the Goblin!
The Goblin attacked you for 3 damage.
stackoverflow has -5 HP remaining.
try this:
int i = 1;
int answer;
int d;
int e;
boolean alive = true;
System.out.println("\n");
System.out.println(enemies[i].getName() + " has appeared!");
System.out.print("\n");
while (alive == true) {
System.out.println("Hitpoints[HP]: " + enemies[i].getHP());
System.out.println("Attack[ATK] : " + enemies[i].getATK());
System.out.println("Mana[MANA] : " + enemies[i].getMANA());
System.out.println("\n");
if (user.getP_HP() > 0) {
System.out.println("[1 - Attack]");
System.out.println("[2 - Flee]");
answer = In.getInt();
System.out.println("\n");
} else if (user.getP_HP() <= 0) {
System.out.println(user.getP_Name() + " has been slain by the " + enemies[i].getName() + "!");
alive = false;
answer = 0; //so it won't execute the rest of the code
}
if (answer == 1) {
d = enemies[i].getHP() - user.getP_ATK();
enemies[i].setHP(d);
System.out.println(user.getP_Name() + " strikes the " + enemies[i].getName() + " for " + user.getP_ATK() + " damage.");
System.out.println(enemies[i].getName() + " has " + enemies[i].getHP() + " HP remaining.");
System.out.println("\n");
if (enemies[i].getHP() > 0) {
e = user.getP_HP() - enemies[i].getATK();
user.setP_HP(e);
System.out.println("The " + enemies[i].getName() + " attacked you for " + enemies[i].getATK() + " damage.");
System.out.println(user.getP_Name() + " has " + user.getP_HP() + " HP remaining.");
System.out.println("\n");
} else if (enemies[1].getHP() <= 0) {
System.out.println(user.getP_Name() + " has slain the " + enemies[i].getName() + "!");
alive = false;
}
} else if (answer == 2) {
System.out.println("You try to run, but fall into a pit of spikes and die!");
alive = false;
}
}
you need to check if you're alive BEFORE asking for an input. Might not be the best solution, but it's a fast one and I hope it points you in the right direction
You actually want to do things in the following order (assuming that you attack):
Ask the player whether they want to attack or flee
You attack
See if you killed the monster; if so, the game is over
The monster attacks
See if the monster killed you; if so, the game is over
Repeat until either #3 or #5 occurs
You reverse #3 and #5.
Also, the following line:
else if (enemies[1].getHP() <= 0)
has what I assume is a typo. I assume that you actually meant to do
else if (enemies[i].getHP() <= 0)
It seems like instead of using else if, what you want is something like this:
// Process both attacks first.
if (user.getP_HP() > 0) {
d = enemies[i].getHP() - user.getP_ATK();
enemies[i].setHP(d);
// ...
}
if (enemies[i].getHP() > 0) {
e = user.getP_HP() - enemies[i].getATK();
user.setP_HP(e);
// ...
}
// Then resolve the deaths immediately after.
if (user.getP_HP() <= 0) {
// ...
alive = false;
}
if (enemies[1].getHP() <= 0) {
// ...
alive = false;
}
The purpose of this program is to build a 10x10 array grid made out of periods (.), allow the user to designate a starting point, and then the program will randomly choose numbers which are assigned to directions for the 'walker' to go. Each time it moves it marks its spot with the next letter in the alphabet (the starting point is marked by A). I haven't done this part yet but I know how I will; if the walker crosses out of the bounds of the array (AKA > 10 or < 0) it will say "you were arrested" and if the variable alpha == 'Z' it way say "You made it home".
The main problem as far as I can tell is with the method processing(), where I draw numbers from getRand (which I have confirmed is working) and then assign them directions which are given to the array. But for some reason when it prints the grid it only shows the starting point, and not the movement of the walker.
Another question I have of lesser importance is if there is a more brief way to display my grid than how I have been (A massive brick of text in a System.out.print)
package walktester;
import java.lang.Math;
import java.util.Random;
import java.util.Scanner;
class DrunkWalker {
private char[][] walkgrid = new char[10][10];
private static int randNSEW;
private int randomnum;
private int startrow;
private int startcol;
private char alpha = 'A';
private int nextrow;
private int nextcol;
public DrunkWalker(int r, int c) {
startrow = r;
startcol = c;
nextrow = startrow;
nextcol = startcol;
for (int i = 0; i < 10; i ++) {
for (int j = 0; j < 10; j++)
walkgrid[i][j] = '.';
}
walkgrid[r][c] = alpha;
}
public static void getRand(){
int x100 = 0;
double randomNum = 0.0;
randomNum = Math.random();
x100 = (int) (randomNum * 100);
randNSEW = x100 % 4;
}
public int getNextRow(){
return nextrow;
}
public int getNextCol(){
return nextcol;
}
public void processing(){
for(int i = 0; i < 26; i ++){
getRand();
if(randNSEW == 0){
nextcol--;
walkgrid[nextrow][nextcol] = alpha++;
}
if(randNSEW == 1){
nextrow++;
walkgrid[nextrow][nextcol] = alpha++;
}
if(randNSEW == 2){
nextcol++;
walkgrid[nextrow][nextcol] = alpha++;
}
if(randNSEW == 3){
nextrow--;
walkgrid[nextrow][nextcol] = alpha++;
}
}
}
public char[][] DisplayGrid() {
System.out.print(
walkgrid[0][0] + " " + walkgrid[0][1] + " " + walkgrid[0][2] + " " + walkgrid[0][3] + " " + walkgrid[0][4] + " " + walkgrid[0][5] + " " + walkgrid[0][6] + " " + walkgrid[0][7] + " " + walkgrid[0][8] + " " + walkgrid[0][9] + "\n" +
walkgrid[1][0] + " " + walkgrid[1][1] + " " + walkgrid[1][2] + " " + walkgrid[1][3] + " " + walkgrid[1][4] + " " + walkgrid[1][5] + " " + walkgrid[1][6] + " " + walkgrid[1][7] + " " + walkgrid[1][8] + " " + walkgrid[1][9] + "\n" +
walkgrid[2][0] + " " + walkgrid[2][1] + " " + walkgrid[2][2] + " " + walkgrid[2][3] + " " + walkgrid[2][4] + " " + walkgrid[2][5] + " " + walkgrid[2][6] + " " + walkgrid[2][7] + " " + walkgrid[2][8] + " " + walkgrid[2][9] + "\n" +
walkgrid[3][0] + " " + walkgrid[3][1] + " " + walkgrid[3][2] + " " + walkgrid[3][3] + " " + walkgrid[3][4] + " " + walkgrid[3][5] + " " + walkgrid[3][6] + " " + walkgrid[3][7] + " " + walkgrid[3][8] + " " + walkgrid[3][9] + "\n" +
walkgrid[4][0] + " " + walkgrid[4][1] + " " + walkgrid[4][2] + " " + walkgrid[4][3] + " " + walkgrid[4][4] + " " + walkgrid[4][5] + " " + walkgrid[4][6] + " " + walkgrid[4][7] + " " + walkgrid[4][8] + " " + walkgrid[4][9] + "\n" +
walkgrid[5][0] + " " + walkgrid[5][1] + " " + walkgrid[5][2] + " " + walkgrid[5][3] + " " + walkgrid[5][4] + " " + walkgrid[5][5] + " " + walkgrid[5][6] + " " + walkgrid[5][7] + " " + walkgrid[5][8] + " " + walkgrid[5][9] + "\n" +
walkgrid[6][0] + " " + walkgrid[6][1] + " " + walkgrid[6][2] + " " + walkgrid[6][3] + " " + walkgrid[6][4] + " " + walkgrid[6][5] + " " + walkgrid[6][6] + " " + walkgrid[6][7] + " " + walkgrid[6][8] + " " + walkgrid[6][9] + "\n" +
walkgrid[7][0] + " " + walkgrid[7][1] + " " + walkgrid[7][2] + " " + walkgrid[7][3] + " " + walkgrid[7][4] + " " + walkgrid[7][5] + " " + walkgrid[7][6] + " " + walkgrid[7][7] + " " + walkgrid[7][8] + " " + walkgrid[7][9] + "\n" +
walkgrid[8][0] + " " + walkgrid[8][1] + " " + walkgrid[8][2] + " " + walkgrid[8][3] + " " + walkgrid[8][4] + " " + walkgrid[8][5] + " " + walkgrid[8][6] + " " + walkgrid[8][7] + " " + walkgrid[8][8] + " " + walkgrid[8][9] + "\n" +
walkgrid[9][0] + " " + walkgrid[9][1] + " " + walkgrid[9][2] + " " + walkgrid[9][3] + " " + walkgrid[9][4] + " " + walkgrid[9][5] + " " + walkgrid[9][6] + " " + walkgrid[9][7] + " " + walkgrid[9][8] + " " + walkgrid[9][9] + "\n"
);
return walkgrid;
}
}
public class WalkTester {
public static void main(String[] args) {
Scanner inpr = new Scanner(System.in);
Scanner inpc = new Scanner(System.in);
Scanner inpchoice = new Scanner(System.in);
int r = 0;
int c = 0;
char choice = 'y';
while(choice == 'y' || choice == 'Y') {
System.out.println("Please enter x coordinate between 1 and 10.");
r = inpr.nextInt();
r = r - 1;
System.out.println("Please enter y coordinate between 1 and 10");
c = inpr.nextInt();
c = c - 1;
if(r < 0 || r > 9 || c < 0 || c > 9){
System.out.println("Invalid Entry. Restart? y/n");
choice = inpchoice.next().charAt(0);
if(choice == 'y' || choice == 'Y'){
continue;
}
else if(choice == 'n' || choice == 'N'){
return;
}
else{
System.out.println("Invalid Entry. Restart? y/n");
choice = inpchoice.next().charAt(0);
}
}
DrunkWalker drunkwalker = new DrunkWalker(r, c);
drunkwalker.DisplayGrid();
System.out.println("Restart? y/n");
choice = inpchoice.next().charAt(0);
if(choice == 'y' || choice == 'Y'){
continue;
}
else if(choice == 'n' || choice == 'N'){
return;
}
else{
System.out.println("Invalid Entry. Restart? y/n");
choice = inpchoice.next().charAt(0);
}
}
}
}
The code that moves the walker is in a method called processing(), but you never call it.
You can make your DisplayGrid() method simpler (and it will still print the same stuff):
public char[][] DisplayGrid() {
for(int y = 0; y < 10; y++) {
for(int x = 0; x < 10; x++) {
System.out.print(walkgrid[x][y] + " ");
}
System.out.println();
}
return walkgrid;
}
Your processing() method needs to check if the walker leaves the bounds of the area. If you don't, you'll get an ArrayIndexOutOfBoundsException.
public boolean processing(){
for(int i = 0; i < 26; i ++){
getRand();
if(randNSEW == 0){
nextcol--;
}
if(randNSEW == 1){
nextrow++;
}
if(randNSEW == 2){
nextcol++;
}
if(randNSEW == 3){
nextrow--;
}
if(nextrow < 0 || nextrow >= 10 || nextcol < 0 || nextcol >= 10) {
return false;
}
walkgrid[nextrow][nextcol] = alpha++;
}
return true;
}
Now you need to call processing() and check the return value to see if the walker succeeded:
DrunkWalker drunkwalker = new DrunkWalker(r, c);
boolean walkerSucceeded = drunkwalker.processing();
drunkwalker.DisplayGrid();
if(walkerSucceeded) {
System.out.println("You made it home");
} else {
System.out.println("You were arrested");
}
And keep in mind (as you will see when you test this), that the walker can cross their own tracks (so you might see some letters missing).
I've written a code for a game that simulates the user and the computer rolling a die and the winner receives 1$ from the loser, with each starting with 2$. The code runs fine, but it doesn't end when either the user or computer reaches 0$ like i had anticipated. Any suggestions?
import java.util.Scanner;
public class ALE_04_RollDice {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
int userMoney = 2;
int compMoney = 2;
int userRoll = (int) (1 + Math.random() * 6);
int compRoll = (int) (1 + Math.random() * 6);
System.out.print("Press 'r' if you would like to roll ");
do {String roll = input.nextLine();
if (roll.equals("r")); {
if (userRoll > compRoll){
userMoney++;
compMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll + ". you won."
+ "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else if (userRoll < compRoll) {
compMoney++;
userMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll +
". you lost" + "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else {System.out.print("The computer rolled " + compRoll + "and you rolled " + userRoll +
". it's a tie" + "\n" + "You have $" + userMoney + " & the computer has $" + compMoney);}
}
}while (userMoney >= 0 || compMoney >=0);
}}
Your while statement is testing for <= 0, but initially both variables are > 0. The while loop will never fire.
First off you have a problem with your while condition money values = 2 for player and comp, so while will never fire..fix that and you could use a do while
do{
statement(s) //block of statements
}while (Boolean expression);
So inside your do{} you could have your statements and conditions..so it will do whatever is inside those braces until the condition inside the while() is met
for example
class DoWhileLoopExample {
public static void main(String args[]){
int i=10;
do{
System.out.println(i);
i--;
}while(i>1);
}
}
You are using the incorrect condition in the while statement.You are testing if any player has >=0 this will always test true and cause an infinite loop. Instead test if BOTH players have >0 and end the game if not.
Also you have a ';' after you if statement. That will cause the code after it to execute all the time.
Here is complete working code:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int userMoney = 2;
int compMoney = 2;
int userRoll = (int) (1 + Math.random() * 6);
int compRoll = (int) (1 + Math.random() * 6);
System.out.print("Press 'r' if you would like to roll ");
do {String roll = input.nextLine();
if (roll.equals("r")) {
if (userRoll > compRoll){
userMoney++;
compMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll + ". you won."
+ "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else if (userRoll < compRoll) {
compMoney++;
userMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll +
". you lost" + "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else {System.out.print("The computer rolled " + compRoll + "and you rolled " + userRoll +
". it's a tie" + "\n" + "You have $" + userMoney + " & the computer has $" + compMoney);}
}
//prompt user to type 'r' to roll again
System.out.println("\n\nPress 'r' if you would like to roll ");
}while (userMoney > 0 && compMoney >0);
System.out.println("\n\nGAME OVER!!!");
}
}
//end main
You want to stop when less than or equal to but you have greater than or equal to.
while (userMoney >= 0 || compMoney >=0) {
Cause of problem:
Your while loop does not run at all, because the condition inside is initially evaluated as false.
while (userMoney <= 0 || compMoney <=0)
This reads: whilst the user has a money less than or equal to 0 OR whilst the computer has money less than or equal to 0 then run the while loop, this will never initially be true as they both the computer and user both start with $2, hence userMoney == 2 and compMoney == 2.
Solution:
Change the condition of the while loop to the following:
while(userMoney>0 || compMoney>0)
then add an if statement which says if the compMoney == 0 or if the userMoney == 0, then break out of the while loop.
if(userMoney == 0 || compMoney == 0){
break;
}