In a blackjack game I give a user prompt to choose if he wants to double down:
while(true){
if(players[i].doubledown == true){
break;
}
System.out.println("Want to double down?\n1)Yes\n2)No\n");
dd = IO.readInt();
if (dd != 1 && dd!= 2){
IO.reportBadInput();
}else{
break;
}
}
int x = 0;
if (dd!=1 && players[i].doubledown == false){
System.out.print("Choose your next move, " + players[i].name + ": \n" + "Points: " + players[i].points + "\n" + "Hint: ");
getHints(players[i]);
System.out.print( "\n1)Hit\n2)Stand\n");
System.out.println();
x = IO.readInt();
}else if(dd == 1 && players[i].doubledown == true){
x = 2;
}else if( dd== 1 && players[i].doubledown == false){
x = 1;
players[i].doubledown = true;
}
if(x ==2 || x ==1){
//
//Stand or Bust
//
}
For some reason it keeps asking me to double down and then after that it's player 2's turn. Why? Any help will be appreciated.
This code will always ask the player to double down, if players[i].doubledown is false. You don't show us the code where you set that flag, so I assume it's always false if it keeps asking you.
If you then answer 1, it goes into the 3rd case of your if statement, which doesn't print anything, so I assume that would make it player 2's turn. If you answer 2, it should ask you to hit or stand... does that happen?
Related
I have a lottery program that will run bets and randomly generate numbers. When the user reaches $5000 in total wins, that user will have an option to cash out $5000 and use the remaining balance to continue the loop. The user will also be able to end the loop if choosing to not cash out. How do I continue a loop based on user input? If the user writes yes, the loop will continue, but I am not sure how to do that. Can someone please help? If the loop is supposed to continue, $5000 removed from the user's total win because of cashout, the remaining balance will be used to play.
I have tried putting the if statement for user input in multiple places in the main loop, but the user budget keeps increasing, it does not subtract $5000.
java.util.Scanner
while (budget > 0) {
lottery = (int) (Math.random() * 100);
guess = (int) (Math.random() * 100);
budget -= 1; // budget = budget-1;
// Get digits from lottery
int lotteryDigit1 = lottery / 10;
int lotteryDigit2 = lottery % 10;
// Get digits from guess
int guessDigit1 = guess / 10;
int guessDigit2 = guess % 10;
System.out.println("The lottery number is " + lottery);
System.out.println("The computer picked number is " + guess);
// Check the guess
if (guess == lottery) {
System.out.println("Exact match: you win $10,000");
totalWin += 1000;
} else if (guessDigit2 == lotteryDigit1 && guessDigit1 == lotteryDigit2) {
System.out.println("Match all digits: you win $3,000");
totalWin += 300;
} else if (guessDigit1 == lotteryDigit1 || guessDigit1 == lotteryDigit2 || guessDigit2 == lotteryDigit1
|| guessDigit2 == lotteryDigit2) {
System.out.println("Match one digit: you win $1,000");
totalWin += 100;
} else
System.out.println("Sorry, no match");
budget += totalWin;
totalWin=0;
if (budget > initBudget)
if ((budget-initBudget) >= 5000) {
System.out.println("You have reached the goal of 5000, we can go home!");
System.out.println("Enter 1 if you would like to cash out and use remaining balance to play and 0 if you would like to stop");
int decison = input.nextInt();
if (decison==1){budget=budget-5000;
System.out.println("Budget After play " + budget);
continue;
}break;
}
System.out.println("Budget After play " + budget);
}
So in my code, I have the loop
System.out.println("Enter 1 if you would like to cash out and use remaining balance to play and 0 if you would like to stop");
int decison = input.nextInt();
if (decison==1){budget=budget-5000;
System.out.println("Budget After play " + budget);
continue;
}break;
}
This loop should receive user input and then subtract 5000 from the total win and use the remaining budget to continue play.. but it is only increasing. Don't understand why it is increasing if I have -5000.
(if possible, please help me change the answer to a yes/no rather than input 1)
I assumed you are using java.util.Scanner. Here is the answer;
System.out.println("Enter yes if you would like to cash out and use remaining balance to play and no if you " +
"would like to stop");
String decison = input.nextLine();
if ("yes".equals(decison))
{
budget = budget - 5000;
System.out.println("Budget After play " + budget);
continue;
}
break; // break the statement.
Erçin Akçay explained how to change the input from an int to a String.
I took a look at your code and made a runnable main method using it, and it works as you would expect. Perhaps the fact that it needs to be 5k from the intial budget is confusing?
if ((budget - initBudget) >= 5000)
Here is the entire class I used to check your code if it is helpful:
import java.util.Scanner;
public class Test {
private static int budget;
private static int lottery;
private static int guess;
private static int totalWin;
private static int initBudget = 4500;
public static void main(String[] args) throws InterruptedException {
Scanner input = new Scanner(System.in);
budget = initBudget;
while (budget > 0) {
lottery = (int) (Math.random() * 100);
guess = (int) (Math.random() * 100);
budget -= 1; // budget = budget-1;
// Get digits from lottery
int lotteryDigit1 = lottery / 10;
int lotteryDigit2 = lottery % 10;
// Get digits from guess
int guessDigit1 = guess / 10;
int guessDigit2 = guess % 10;
System.out.println("The lottery number is " + lottery);
System.out.println("The computer picked number is " + guess);
// Check the guess
if (guess == lottery) {
System.out.println("Exact match: you win $10,000");
totalWin += 1000;
} else if (guessDigit2 == lotteryDigit1 && guessDigit1 == lotteryDigit2) {
System.out.println("Match all digits: you win $3,000");
totalWin += 300;
} else if (guessDigit1 == lotteryDigit1 || guessDigit1 == lotteryDigit2 || guessDigit2 == lotteryDigit1
|| guessDigit2 == lotteryDigit2) {
System.out.println("Match one digit: you win $1,000");
totalWin += 100;
} else {
System.out.println("Sorry, no match");
}
budget += totalWin;
totalWin = 0;
if (budget > initBudget) {
if ((budget - initBudget) >= 5000) {
System.out.println("You have reached the goal of 5000, we can go home!");
System.out.println(
"Enter 1 if you would like to cash out and use remaining balance to play and 0 if you "
+ "would like to stop");
int decison = input.nextInt();
if (decison == 1) {
budget = budget - 5000;
System.out.println("Budget After play " + budget);
continue;
}
break;
}
}
System.out.println("Budget After play " + budget);
}
}
}
You can change your code like this:
System.out.println("Enter yes if you would like to cash out and use remaining balance to play and no if you would like to stop");
String decision = input.next();
if ("Yes".equalsIgnoreCase(decision)) { // Cashing Out
budget = budget - 5000;
System.out.println("Budget After play " + budget);
continue;
}
break; // breaking the loop (if user enters anything other than yes)
Here I have used String (to store User's response as a word). If he enters Yes, yes or YES (ignoring the case, it will be considered that user wants to cash out) the loop will not break.
I am in the process of creating the java game PIG, each player gets to roll a dice and each turn is added to a score and the first player to get 100 is the winner, the players can choose to roll the dice or hold, if the player rolls and land a 1 their turn is over and all points go to 0, if a player chooses to hold all points gained during the turn are added to her school.
I do however have some issues that i cannot work out, when a user rolls a 1 and their turn would be over and no points given, instead the program gives no output and does not carry on playing (going into an infinite loop??).
edit:
i have since been able to solve the previous issues however i now only get an infinite loop when the program is ran and i do not understand why, Also does anyone know how to make the game replayable after a game has ended?
below is my new code:
//Callum Fawcett
//Game of Pig
//Create: 20/02/2019
//Version 0.1
import java.util.Scanner;
import java.util.Random;
public class game2
{
public static void main(String[] args)
{
int playerScores = 0;
int playerTotal = 0;
int computerScores = 0;
int computerTotal = 0;
int dice;
boolean gameOver = false;
boolean turnOver = false;
char repeat;
String input;
Scanner keyboard = new Scanner(System.in);
Random rand = new Random();
System.out.println("Welcome to the game of Pig!\n");
while (gameOver == false)
{
do
{
dice = rand.nextInt(6) + 1;
System.out.println("You rolled: " + dice);
if (dice == 1)
{
playerScores = 0;
System.out.print("You lose your turn! ");
System.out.println("Your total is " + playerTotal);
turnOver = true;
}
else
{
playerScores += dice;
System.out.print("Your turn score is " +
playerScores);
System.out.println(" If you hold you will have " +
playerScores + " points.");
System.out.println("Enter 'r' to roll " +
"again, 'h' to hold.");
input = keyboard.nextLine();
repeat = input.charAt(0);
if (repeat == 'h')
break;
}
} while(turnOver == false || dice != 1);
playerTotal += playerScores;
System.out.println("Your score is " +
playerTotal);
playerScores = 0;
if (playerTotal >= 100)
{
System.out.println("YOU WIN!");
gameOver = true;
}
System.out.println();
System.out.println("It is the computer's turn.");
do
{
dice = rand.nextInt(6) + 1;
System.out.println("The computer rolled: " +
dice);
if(dice == 1)
{
computerScores = 0;
System.out.print("The computer lost its turn!");
System.out.print(" Computer total is " +
computerTotal);
turnOver = false;
}
else
{
computerScores += dice;
if(computerScores >= 20 || (computerTotal +
computerScores) >= 100)
System.out.println("The computer holds");
turnOver = false;
}
} while (dice != 1 || computerScores < 20);
computerTotal += computerScores;
System.out.println("The computer's score is " +
computerTotal + "\n");
computerScores = 0;
if (computerTotal >= 100)
{
System.out.println("THE COMPUTER WINS!");
gameOver = true;
}
if(keyboard!=null)
keyboard.close();
}
}
}
this is an output i get :
TheRealFawcett:lab5 therealfawcett$ java game2
Welcome to the game of Pig!
You rolled: 6
Your turn score is 6 If you hold you will have 6 points.
Enter 'r' to roll again, 'h' to hold.
r
You rolled: 4
Your turn score is 10 If you hold you will have 10 points.
Enter 'r' to roll again, 'h' to hold.
r
You rolled: 1
You lose your turn! Your total is 0
Your score is 0
It is the computer's turn.
The computer rolled: 2
The computer rolled: 2
The computer rolled: 1
The computer lost its turn! Computer total is 0The computer's score is
0
You rolled: 2
Your turn score is 2 If you hold you will have 2 points.
Enter 'r' to roll again, 'h' to hold.
Exception in thread "main" java.lang.IllegalStateException: Scanner
closed
at java.base/java.util.Scanner.ensureOpen(Scanner.java:1150)
at java.base/java.util.Scanner.findWithinHorizon(Scanner.java:1781)
at java.base/java.util.Scanner.nextLine(Scanner.java:1649)
at game2.main(game2.java:50)
TheRealFawcett:lab5 therealfawcett$
I am fairly new to programming and have decided to take on a project where I create a game in the console. The user has the options to move up, down, left, or right from the center of an area that is a 3x3 grid. One of the x,y locations is marked a 'bad' square and the game ends when the user's x and y are equal to that of the bad square's. The bad squares location is x = 1 and y = 3.
The problem I have is that when the user enters Up or Left (hence the users y becomes 3 or the users x becomes 1) and the game ends even though one of the other axis values does not match the bad squares.
Here is my code:
public static void main (String[]args){
//scanner
Scanner userIn = new Scanner(System.in);
//string that will get users value
String movement;
//strings that are compared to users to determine direction
String up = "Up";
String down = "Down";
String left = "Left";
String right = "Right";
//starting coordinates of user
int x = 2;
int y = 2;
//coordinates of bad square
int badx = 1;
int bady = 3;
//message telling user options to move (not very specific yet)
System.out.println("Up, Down, Left, Right");
//do while loop that continues until
do {
movement = userIn.nextLine();
//checking user input and moving them accordingly
if (movement.equals(up)) {
y++;
} else if (movement.equals(down)) {
y--;
} else if (movement.equals(left)) {
x--;
} else if (movement.equals(right)) {
x++;
} else {
System.out.println("Unacceptable value");
}
//checking if user is out of bounds, if user tries to leave area, x or y is increased or decreased accordingly
if (x < 0 || y < 0 || x > 3 || y > 3) {
System.out.println("Out of bounds");
if (x < 0) {
x++;
} else if (y < 0) {
y++;
} else if (x > 3) {
x--;
} else if (y > 3) {
y--;
}
}
//message showing user x and y coordinates
System.out.println("x =" + x + " y =" + y);
} while (y != bady && x != badx); //what checks to see if user has come across the bad square
//ending message (game ends)
System.out.println("Bad Square. Game over.");
}
Your while(y != bady && x != badx) test tests y isn't bad AND x isn't bad therefore it only takes one of these to be false for your loop to cease.
An easy fix might be to swap your logic around a little.
while(!(y == bady && x == badx))
If you think about how your conditional statement is phrased while(y != bady && x != badx) you will see that when either x = 1 or y = 3, one of the sides in the AND statement evaluates to false and causes the whole condition to be false. You could handle it by instead writing:
while(y != bady || x != badx)
Just set logic OR in condition
while(y != bady || x != badx);
&& matters that both conditions should be true
I just started coding with more complex methods than the main method. I was given an assignment to make a race with three coins. Whichever coin flips 2 heads and 2 tails first in that order wins. I coded an if else statement to determine which coin wins but neither of the if statements are ever executed. Please tell me if you see an error in my if else statements or somewhere else. I also have to other programs of code that include other methods.
public class FlipRace
{
public static void main (String[] args)
{
final int GOALHEAD = 2;
final int GOALTAIL = 2;
int count1 = 0, count2 = 0, count3 = 0, count10 = 0, count20 = 0, count30 = 0;
// Create three separate coin objects
Coin coin1 = new Coin();
Coin coin2 = new Coin();
Coin coin3 = new Coin();
while (count1 <= GOALHEAD && count10 <= GOALTAIL || count2 <= GOALHEAD && count20 <= GOALTAIL || count3 <= GOALHEAD && count30 <= GOALTAIL)
{
coin1.flip();
coin2.flip();
coin3.flip();
// Print the flip results (uses Coin's toString method)
System.out.print ("Coin 1: " + coin1);
System.out.println (" Coin 2: " + coin2);
System.out.println (" Coin 3: " + coin3);
// Increment or reset the counters
if (coin1.isHeads())
count1++;
else
count10++;
if (coin2.isHeads())
count2++;
else
count20++;
if (coin3.isHeads())
count3++;
else
count30++;
}
// Determine the winner
if (count1 == GOALHEAD && count10 == GOALTAIL)
System.out.println ("Coin 1 wins!");
else if (count2 == GOALHEAD && count20 == GOALTAIL)
System.out.println ("Coin 2 wins!");
else if (count3 == GOALHEAD && count30 == GOALTAIL)
System.out.println ("Coin 3 wins!");
else
System.out.println ("It's a TIE!");
}
}
Here is my output:
Coin 1: Heads Coin 2: Heads
Coin 3: Tails
Coin 1: Heads Coin 2: Heads
Coin 3: Heads
Coin 1: Heads Coin 2: Tails
Coin 3: Heads
Coin 1: Heads Coin 2: Heads
Coin 3: Tails
Coin 1: Heads Coin 2: Tails
Coin 3: Heads
It's a TIE!// this message comes up every time because something is wrong
try changing your comparison to
if (count1 >= GOALHEAD && count10 >= GOALTAIL)
System.out.println ("Coin 1 wins!");
else if (count2 >= GOALHEAD && count20 >= GOALTAIL)
System.out.println ("Coin 2 wins!");
else if (count3 >= GOALHEAD && count30 >= GOALTAIL)
System.out.println ("Coin 3 wins!");
else
System.out.println ("It's a TIE!");
of course another way would to simply debug your code and inspect the values
I don't understand how your code would solve the problem. If I understand it right, you want the first coin that shows the combination H-H-T-T. Now, you are counting the heads and tails in ANY order. So, if you have H-T-H-T for the first coin and H-H-H-T and H-T-T-T for the second and third respectively, the first one wins.
In order to solve the problem considering the order of heads and tails, I think you should change the if-else statement for each coin (I'll make it only for coin1 here):
if (coin1.isHeads()) {
if (count1 < 2 && count2 == 0) { //less than 2 heads and zero tails
count1++;
} else {
count1 = 0;
count10 = 0;
}
} else { //tails
if (count1 == 2 && count10 < 2) { //we already have two heads and 0 or 1 tail
count10++;
} else { // either less than two heads or too many tails - we have to restart!
count1 = 0;
count10 = 0;
}
}
You should also change the while statement... You want to stop when you have two heads ant two tails for any coin. So, it'd be something like this:
while (!(count1 == 2 && count10 == 2) && !(count2 == 2 && count20 == 2) && ....) {...}
The aim of this program is to make a Rock Paper Scissors game. I have succeeded in making it however I can not get it to loop no matter what I try. I tried:
while (index = 0)
while (index < gamesCount)
However, while my index is 0 and my condition says while (index != 0), it seems to be the only condition that runs the program but it will not loop regardless. How can I get my game to loop?
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random randomGen = new Random();
//Variables
String player1;
int cpu;
int start = 1;
int end = 3;
int index = 0;
// 1 = Rock | 2 = Scissors | 3 = Paper
//Code
System.out.println("Welcome to Rock, Paper, Scissors!");
while (index != 0) {
System.out.print("Rock, Paper, or Scissors?: ");
player1 = in.nextLine();
cpu = randomGen.nextInt(3);
System.out.println(cpu);
if (player1.equals("Rock") && (cpu == 2)) {
System.out.println("You lose!");
} else if (player1.equals("Rock") && (cpu == 1)) {
System.out.println("You win!");
} else if (player1.equals("Rock") && (cpu == 0)) {
System.out.println("Draw!");
}
// --------------------
if (player1.equals("Scissors") && (cpu == 2)) {
System.out.println("Draw!");
} else if (player1.equals("Scissors") && (cpu == 1)) {
System.out.println("You win!");
} else if (player1.equals("Scissors") && (cpu == 0)) {
System.out.println("You lose!");
}
//---------------------
if (player1.equals("Paper") && (cpu == 2)) {
System.out.println("You lose!");
} else if (player1.equals("Paper") && (cpu == 1)) {
System.out.println("You win!");
} else if (player1.equals("Paper") && (cpu == 0)) {
System.out.println("Draw!");
}
}
}
}
You have your index variable set to 0. The condition of the while loop is saying, if index does not equal 0, execute the code in the loop. Since your index equals 0, the instructions in the loop will not be executed. Also, you will need to update the index variable in the loop so that if the condition you are looking for is met, the code will stop looping.
ie:
int gamesPlayed = 0;
int gamesRequested = 3; // or get this from the user
while (gamesPlayed < gamesRequested){
String player1Choice = in.nextLine();
if(!"".equals(player1)){
// your code
gamesPlayed++;
} else {
System.out.print("Rock, Paper, or Scissors?: ");
}
}
Two mistakes:
while (index != 0);
this is the entire loop. it ends either at the end of the { } block (which you don't have), or at the first ; which is immediately after the statement.
Correct this, though, and it still won't loop:
int index = 0;
// 1 = Rock | 2 = Scissors | 3 = Paper
//Code
System.out.println("Welcome to Rock, Paper, Scissors!");
while (index != 0);
index = 0, so (index != 0) will never return true.
Your index variable is set to a value of 0.
Your while loop says
while (index != 0);
Which means, while the index isn't 0, run my code. The problem is your code will never run then because your index value is always 0.
Try changing it to another value (say 5 for example), and it should work now.
:)