How come my if else statements don't execute? - java

First of all, I have found two other threads that have similar questions. There problem is that they didn't use the right equal sign for string and not formatting the if statements correctly for their particular problem.
For my assignment, I need to create a game called Pig where the player verses a computer in getting 100 points first in rolling pairs of dice. If the player rolls 1 on one turn, they get no additional points. If the player rolls two 1's, then they lose all their points. I have not coded the computer's turn yet, just focusing on the player. Please tell me what I am doing wrong. Thank you very much in advance.
import java.util.Scanner;
public class FourFive
{
public static void main (String[] args)
{
Pigs myopp = new Pigs();
Scanner scan = new Scanner (System.in);
final int Round = 20;
int num1, num2;
int roundTotal = 0;
int playerTotal = 0;
int compTotal = 0;
int win = 100;
int turnOver = 1;
Pigs die1 = new Pigs();
Pigs die2 = new Pigs();
String play = "y";
System.out.println("Type y to play");
play = scan.nextLine();
while (play.equalsIgnoreCase("y"))
{
for (int roll = 1; roll <= 6; roll++)//Each die has 6 sides
{
num1 = die1.roll();//rolls first die
num2 = die2.roll();//rolls second die
int points = num1 + num2;// adds dies up to get total for this turn
System.out.println("You roll " + num1 + " and " + num2);
if (num1 == 1 || num2 == 1)//If either of the dies roll 1, no points
points += 0;
else if (num1 == 1 && num2 == 1)//if both are 1, lose ALL points
playerTotal = 0;
else
System.out.println("you earned " + points + " this round");
playerTotal += points; total number of points per round added
System.out.println("You have a total of " + playerTotal);
System.out.println("Type y to play");
play = scan.nextLine();
}
}
}
}
My Output:
Type y to play
y
You roll 4 and 2
you earned 6 this round
You have a total of 6
Type y to play
y
You roll 6 and 5
you earned 11 this round
You have a total of 17
Type y to play
y
You roll 1 and 1
You have a total of 19 //total should be 0 because of the two 1's
Type y to play
y
You roll 6 and 3
you earned 9 this round
You have a total of 28
Type y to play
y
You roll 1 and 1
You have a total of 30 //total should be 0 because of the two 1's
Type y to play
y
You roll 6 and 4
you earned 10 this round
You have a total of 40
Type y to play
y
You roll 5 and 2
you earned 7 this round
You have a total of 47
Type y to play
y
You roll 5 and 1
You have a total of 53 //shouldn't add any additional points because of the "1"
Type y to play

If num1 is 1, then the first if condition takes it. It will not check the 'else if' condition. Similarly, if num2 is 1, the if condition takes it. So put your && condition first.
if (num1 == 1 && num2 == 1)//if both are 1, lose ALL points
playerTotal = 0;
else if (num1 == 1 || num2 == 1)//If either of the dies roll 1, no points
points += 0;
else
System.out.println("you earned " + points + " this round");

Your if logic is flawed and a bit redundant. Try this:
if (num1 == 1 && num2 == 1) {
playerTotal = 0;
}
else if (num1 != 1 && num2 != 1) {
playerTotal += points;
System.out.println("you earned " + points + " this round");
}
System.out.println("You have a total of " + playerTotal);

Related

rolling 2 dice randomly (java)

Two dice will be rolled and 2 random numbers between 1 and 6 will be generated. The sum will
be taken from the 2 numbers and used to decide what is next. If user's sum is 3, 5, 7, 9,11 then they
lose. If the sum is 4, 6, 8, 10 then they win. If sum is 2, 12 then the program automatically rolls the
dice again until the user wins or loses.
Create a game for the above algorithm with following constructs in it:
Game should ask the user to input his/ her name.
Game should be able to generate random numbers between 1 - 6.
Program should be able to show 3 alternate paths
a. Win : when the random number is in 4 , 6, 8, 10
b. Loose: 3,5,7,9,11
c. Play again: 2, 12
Basically I need keep getting a new random number if I get sum of 2 or 12 from 2 dice and that has to go into the loop again and again
public class assessmentrollingdicedemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Enter User Name: ");
String userName = sc.next();
Random r = new Random();
int firstRoll = r.nextInt(6);
int secondRoll = r.nextInt(6);
firstRoll+= 1;
secondRoll+= 1;
int timesWin = 0;
int timesLose = 0;
int sumOfdice = firstRoll + secondRoll;
do
{
System.out.println("Die 1: "+ firstRoll);
System.out.println("Die 2: "+ secondRoll);
System.out.println("total: "+ sumOfdice);
if(sumOfdice == 4 || sumOfdice == 6 || sumOfdice == 8 || sumOfdice == 10)
{
System.out.println("Win");
timesWin++;
}
if(sumOfdice == 3 || sumOfdice == 5 || sumOfdice == 7 || sumOfdice == 9 || sumOfdice == 11)
{
System.out.println("Lose");
timesLose++;
}
else
{
System.out.println("Play Again");
}
} while(sumOfdice == 12 || sumOfdice ==2);
System.out.println("You won " + timesWin + "times");
System.out.println("You lost " + timesLose + "times");
}
}
What I expected was rolling again should only applies to when sum of dice is 2 or 12 but I get infinite loops. Please help me if you know the answer.
sumOfdice should be assigned a new value in the loop
in the else statement you should re roll the dices
...
else{
System.out.println("Play Again");
firstRoll = r.nextInt(6);
secondRoll = r.nextInt(6);
sumOfdice = firstRoll + secondRoll;
}
...
otherwise the while() will loop over the same value.

Dice game with two players, 3 die choices and cards

I am trying to write code for a game that has a player and a computer roll dice until one, or both, reach 250( its possible for them to tie). The player and the computer can choose from 1 of 3 die choices. One - 24 sided tie, two - 10 sided die, or three - 6 sided die. There is a bonus for the 10 and 6 sided die if the die are all the same. There are 2 "lakes" where if the player lands in them the player has to go back to the lower number right before the beginning of the lake, there is also a muddy swamp where every move the player makes while in the swamp is cut in half. For every 10 spots (10, 20, 30, 40 ETC.) the player randomly draws a card. There are 11 different cards the player can randomly get:
1-4: player moves ahead a random amount from 1-6
5: player moves ahead a random amount from 4-11 (random 8 + 4)
6: player moves to where the other player is (see below)
7: player moves back to the beginning (moves to location 0)
8-9: player moves back a random amount from 1-6
10-11: player moves back a random amount from 4-11
I have a few problems. My first problem is that the die rolls do not change after every turn, they will remain the same. So if I choose 3 die I might get 3 random numbers, if I choose those die again I will get those same 3 numbers.
I also cannot seem to get the players die count to correctly update. If the player rolls 18 total points and the next turn he rolls 14 the count will go from 18 to 14.
My third problem is it seems like no matter what I do the print statement for the lakes,muddy patch and the winner announcement always print. I have tried a few different things and nothing seems to work.
I am new at code writing ( this is my 4th program written) and do not have extensive knowledge to know what is wrong. The code does not have to be expertly done, I just would like it to work properly. Any and all help is greatly appreciated.
/*This program will create a "Board" game. Each player can choose
from several different types of die. The computer and user will take
turns "rolling" a dice. There are several obstacles that can send one
of the players back. The goal is to get above 250*/
import java.util.*;
public class Project4 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
//assigning variables
int p1, p2;
p1=p2=0;
int spacesmoved = 0;
//Setting up the randomization of the 24 sided die
int minimum1 = 1;
int maximum1 = 24;
Random rn1 = new Random();
int range1 = maximum1 - minimum1 + 1;
int die1 = rn1.nextInt(range1) + minimum1;
//Setting up the randomization of the 10 sided die
int minimum2 = 1;
int maximum2 = 10;
Random rn2 = new Random();
int range2 = maximum2 - minimum2+ 1;
int die2 = rn2.nextInt(range2) + minimum2;
int die22 = rn2.nextInt(range2) + minimum2;
int die222 = rn2.nextInt(range2) + minimum2;
//Setting up the randomization of the 6 sided die
int minimum3 = 1;
int maximum3 = 10;
Random rn3 = new Random();
int range3 = maximum3 - minimum3+ 1;
int die3 = rn3.nextInt(range3) + minimum3;
int die33 = rn3.nextInt(range3) + minimum3;
int die333 = rn3.nextInt(range3) + minimum3;
//Setting a loop for the players to take turns until one, or both, reach > 250
while (p1 <= 250 && p2 <= 250) {
{System.out.println(" Current positions. Player: " + p1 + " Computer: " + p2);
System.out.println("Which die would you like to roll? die1(1) = one 24-sided die, die2(2) = two 10-sided dice, die3(3) = three 6-sided dice: ");
String diechoice = in.nextLine().toLowerCase();
//Getting the die roll if the player chooses the 24 sided die
if (diechoice.equals ("1")) {
spacesmoved = (die1);
System.out.println("Player rolled a " + die1);
System.out.println("Player moves forward " + die1 +" spaces");
p1+=spacesmoved;
}
//Getting the die roll if the player chooses the two 10 sided die
if (diechoice.equals ("2")) { spacesmoved = (die2 + die22);
System.out.println("First die is " + die2);//TESTTTT
System.out.println("Second die is a " + die22);//TEST
System.out.println(die2 + die22);//TESTTTTtttt
if (die2 == die22); {
spacesmoved = (die2 + die22 + die222);
System.out.println("Player rolled doubles, player gets to roll a 3rd 10 sided die");
System.out.println("Players 3rd dice roll is " + die222);
System.out.println("Player moves forward a total of " + spacesmoved + " spots");
p1 += spacesmoved;
}
// player1spot = (currentspot + spacesmoved);
}
//Getting the die roll if the player chooses three 6 sided die
if (diechoice.equals("3")) { spacesmoved = (die3 + die33 + die333);
System.out.println("die 1 is " + die3);
System.out.println("die 2 is " + die33);
System.out.println("die 3 is " + die333);
System.out.println("Player 1 moves forward a total of " + spacesmoved + " spots");
{ if (die3 == die33)
if (die33 == die333)
spacesmoved = ( spacesmoved * 2);
p1 += spacesmoved;
}}
/*Setting up the lakes and muddy patch. If the player lands in a lake he goes back
to the lower edge of the lake. If in the mud his moves are cut in half ONLY while in the mud */
{if (spacesmoved >= (83) || spacesmoved <= (89)); spacesmoved = (82);
System.out.println("Player landed in a lake, player goes back to space " + spacesmoved);
if (spacesmoved >= (152) || spacesmoved <= (155)); spacesmoved = (151);
System.out.println("Player landed in a lake, player goes back to space " + spacesmoved);
if (spacesmoved >= (201) || spacesmoved <= (233)); spacesmoved = (spacesmoved / 2);
System.out.println("Player landed in mud, players turns are cut in half until player gets out");
}
//Setting up the random cards if the player lands on a 10
if (p1 % 10==0);
{ int minimum4 = 0;
int maximum4 = 11;
Random rn4 = new Random();
int range4 = maximum4 - minimum4 + 1;
int card = rn4.nextInt(range4) + minimum4;
//if player gets a card that moves them ahead a random number between 1-6
if (card >=4);
int minimum = 0;
int maximum = 6;
Random rn = new Random();
int range = maximum - minimum + 1;
int cardmove = rn.nextInt(range) + minimum;
p1 = cardmove;
//if player gets a card that moves them ahead a random number between 4-11
if (card == 5);
int minimum5 = 4;
int maximum5 = 11;
Random rn5 = new Random();
int range5 = maximum5 - minimum5 + 1;
int cardmove5 = rn5.nextInt(range5) + minimum5;
p1 = cardmove5;
//if player gets a card that moves them to the spot of the other player
if (card == 6);
p2 = p1;
//if player gets a card that moves them back to 0 (moves location to 0)
if (card ==7);
p1 = 0;
//if player gets a card that moves them back between 1-6 spaces
if (card == (8) || card == 9);
int minimum6 = 1;
int maximum6 = 6;
Random rn6 = new Random();
int range6 = maximum6 - minimum6 + 1;
int cardmove6 = rn6.nextInt(range6) + minimum6;
//if player gets a card that moves them back between 4-11 spaces
if (card == (10) || card == 11);
int minimum7 = 4;
int maximum7 = 11;
Random rn7 = new Random();
int range7 = maximum7 - minimum7 + 1;
int cardmove7 = rn7.nextInt(range7) + minimum7;
}
//Setting up the computers turn
System.out.println("Computers turn");
{
int minimum = 0;
int maximum = 2;
Random rn = new Random();
int range = maximum - minimum + 1;
int computersturn = rn.nextInt(range) + minimum;
//If computer randomly chooses a 24 sided die
spacesmoved = (die1);
System.out.println("Computer rolled a " + die1);
System.out.println("Computer moved " + die1 +" spaces");
p2+=spacesmoved;
}
//If the computer randomly chooses the two 10 sided die
if (diechoice.equals ("die2")) { spacesmoved = (die2 + die22);
System.out.println("First die is " + die2);//TESTTTT
System.out.println("Second die is a " + die22);//TEST
System.out.println(die2 + die22);//TESTTTTtttt
if (die2 == die22); {
spacesmoved = (die2 + die22 + die222);
System.out.println("Computer rolled doubles, player gets to roll a 3rd 10 sided die");
System.out.println("Computer 3rd dice roll is " + die222);
System.out.println("Computer moves a total of " + spacesmoved + " spots");
p2 += spacesmoved;
}
}
//If the computer randomly chooses three 6 sided die
if (diechoice.equals("die3")) { spacesmoved = (die3 + die33 + die333);
System.out.println("die 1 is " + die3);
System.out.println("die 2 is " + die33);
System.out.println("die 3 is " + die333);
System.out.println("Computer 1 moves a total of " + spacesmoved + " spots");
{ if (die3 == die33)
if (die33 == die333)
spacesmoved = ( spacesmoved * 2);
p2 += spacesmoved;
}
//Setting the lakes and mud for the computer
if (spacesmoved >= (83) || spacesmoved <= (89)); spacesmoved = (82);
System.out.println("Computer landed in a lake, player goes back to space " + spacesmoved);
if (spacesmoved >= (152) || spacesmoved <= (155)); spacesmoved = (151);
System.out.println("Computer landed in a lake, player goes back to space " + spacesmoved);
if (spacesmoved >= (201) || spacesmoved <= (233)); spacesmoved = (spacesmoved / 2);
System.out.println("Computer landed in mud, players turns are cut in half until player gets out");
//Setting up the cards for the computer
if (p1 % 10==0);
{ int minimum4 = 0;
int maximum4 = 11;
Random rn4 = new Random();
int range4 = maximum4 - minimum4 + 1;
int card = rn4.nextInt(range4) + minimum4;
//if computer gets a card that moves them ahead a random number between 1-6
if (card >=4);
int minimum = 0;
int maximum = 6;
Random rn = new Random();
int range = maximum - minimum + 1;
int cardmove = rn.nextInt(range) + minimum;
//if computer gets a card that moves them ahead a random number between 4-11
if (card == 5);
int minimum5 = 4;
int maximum5 = 11;
Random rn5 = new Random();
int range5 = maximum5 - minimum5 + 1;
int cardmove5 = rn5.nextInt(range5) + minimum5;
//if computer gets a card that moves them to the spot of the other player
if (card == 6);
p1 = p2;
//if computer gets a card that moves them back to 0 (moves location to 0)
if (card ==7);
p1 = 0;
//if computer gets a card that moves them back between 1-6 spaces
if (card == (8) || card == 9);
int minimum6 = 1;
int maximum6 = 6;
Random rn6 = new Random();
int range6 = maximum6 - minimum6 + 1;
int cardmove6 = rn6.nextInt(range6) + minimum6;
//if computer gets a card that moves them back between 4-11 spaces
if (card == (10) || card == 11);
int minimum7 = 4;
int maximum7 = 11;
Random rn7 = new Random();
int range7 = maximum7 - minimum7 + 1;
int cardmove7 = rn7.nextInt(range7) + minimum7;
}
}
//Writing a final statment showing the winner, or if both tied.
{ if (p1 > p2);
System.out.println("Player 1 wins! Good job!");
if (p2 >p1);
System.out.println("Computer wins! Better luck next time!");
if (p2 == p1);
System.out.println("The game ends in a tie!");
}
}
}
}
}
Here are the things I noticed in relation to the three problems you mentioned:
Problem number 1:
You are setting the values of the dice at the very beginning of code execution. From that point on, you aren't changing them at all. That is the cause of the problem of always rolling the same numbers every turn. You might be thinking that every time you use die1 or any of the other die variables, that it is re-executing the code at the top of your file, but it doesn't.
The code at the top of your file is executed only once and then the value stored in that variable is used for the rest of the program execution. Until you change it. So you would want something more like this:
//Getting the die roll if the player chooses the 24 sided die
if (diechoice.equals ("1")) {
die1 = rn1.nextInt(range1) + minimum1;
System.out.println("Player rolled a " + die1);
System.out.println("Player moves forward " + die1 +" spaces");
p1+=die1;
}
You would also need to change that in the other cases where the die is rolled.
Another benefit to doing it this way is that you really only need one random number generator. You don't actually need one for each die. You can use the same one for all die rolls.
Problem number 2:
I'm not sure exactly what is going wrong with die rolls, if there really is something going wrong there, but I did notice a few places where you'll want to change what is done to p1 and p2:
When the player gets a card that moves them ahead, you'll want to use += instead of =. i.e. p1 += cardmove5 instead of p1 = cardmove5
When the player gets a card that moves them back, it looks like you forgot to add the p1 -= cardmove statements.
Also, make sure you have p1 and p2 in the right places. For example, I'm thinking that on the computer's turn, if they get the card to move them to the other player's spot, you meant to do p2 = p1, but instead you have p1 = p2. Same with the computer going back to 0. You have p1 = 0, but it seems like you would want p2 = 0. So just be careful about that. (Also be careful about copy paste. I'm guessing that's why that happened)
Problem number 3:
This problem looks like it's caused by the fact that you are using the || operator where you should be using &&. When you use ||, you are effectively saying "or". So this first statement
if (spacesmoved >= (83) || spacesmoved <= (89))
reads as "if spacesmoved is greater than or equal to 83 OR less than or equal to 89"... Think about that for a second. Is there any number that is NOT greater than 83 OR less than 89? The answer is no. EVERY number will satisfy this condition. You would want to use &&, which means "and" like this:
if (spacesmoved >= (83) && spacesmoved <= (89))
"if spacesmoved is greater than or equal to 83 AND less than or equal to 89", which would only work for numbers between 83 to 89 inclusive.
You will also want to remove the semicolons after your "if" statements in that block and the other similar blocks. If you don't, the code inside those conditions won't get executed. That's actually a really tough bug to find when it happens.
Another thing to know is that when you want multiple things to be executed in an "if" condition, you must enclose it in curly braces {}, otherwise, only the first line will be included in the condition, and any following lines will be executed unconditionally. That is another fact that is causing this third problem.
One last thing is that you should try using "else if" and "else" statements. It will help your code flow make more sense. I'm not going to do all the work for you, but this code block should probably look more like this:
if (p1 >= (83) && p1 <= (89))
{
p1 = (82);
System.out.println("Player landed in a lake, player goes back to space " + p1);
}
else if (p1 >= (152) && p1 <= (155))
{
p1 = (151);
System.out.println("Player landed in a lake, player goes back to space " + p1);
}
else if (p1 >= (201) && p1 <= (233))
{
spacesmoved = (spacesmoved / 2);
p1 -= spacesmoved;
System.out.println("Player landed in mud, players turns are cut in half until player gets out");
}
Bonus Tip
You're learning well, and it seems you are thinking of code flow pretty well. Just keep working and learning and you'll get it.
Look into your usage of parentheses. Using them doesn't hurt anything, but you are using them WAY more than you need.
Good luck! And keep learning!

global variable not recognizing user inputed numbers

import java.util.Scanner;
public class Blackjack {
class Commands {
static final String yes = "yes";
static final String no = "no";
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Opponent player2 = new Opponent();
double AiCard1 = 0;
double AiCard2 = 0;
double AiCard3 = 0;
double AiTotalcard3 = AiCard1 + AiCard2 + AiCard3;
double card1 = 0;
double card2 = 0;
double card3 = 0;
double card4 = 0;
double total2 = card1 + card2 + card3 + card4;
double total = card1 + card2 + card3;
System.out.println("Hello and Welcome to my custom version of blackjack!");
System.out.println("You will start off with $300");
System.out.println();
System.out.println("Do you want to read the rules before playing?");
System.out.print("Press 1 if yes, press 2 for no");
int choice = input.nextInt();
switch (choice) {
case 1:
System.out.println("You have 4 cards to get as close to 21 as possible. Whoever is closest to 21 wins");
break;
default:
break;
}
int balance = 300;
System.out.println("Your bank balance is $" + balance);
//user places a bet
System.out.println("Place a bet");
int bet = input.nextInt();
System.out.println("You placed a bet of " + bet);
//this is the AI
AiCard1 = Math.random() * 12 + 1;
AiCard1 = Math.round(AiCard1);
AiCard2 = Math.random() + 12 + 1;
AiCard2 = Math.round(AiCard2);
double AiTotal2cards = AiCard1 + AiCard2;
if(AiTotal2cards < 15) {
AiCard3 = Math.random() * 12 + 1;
AiCard3 = Math.round(AiCard3);
AiTotalcard3 = AiCard1 + AiCard2 + AiCard3;
}
card1 = Math.random() * 12 + 1;
card1 = Math.round(card1);
System.out.println("Your first card was a " + card1);
System.out.println();
card2 = Math.random() * 10 + 1;
card2 = Math.round(card2);
System.out.println("Your second card was a " + card2);
System.out.println();
System.out.println("Your cards add up to " + (card1 + card2));
System.out.println("Do you want to add another card?");
String answer = input.next();
here:
if(answer.equals(Commands.yes)) {
card3 = Math.random() * 12 + 1;
card3 = Math.round(card3);
System.out.println("Your third card was a " + card3);
System.out.println("Your cards add up to " + (card1 + card2 + card3));
total = card1 + card2 + card3;
if(total > 21) {
System.out.println("You lose");
break here;
}
System.out.println("Do you want to add another card?");
String answer1 = input.next();
if(answer1.equals(Commands.no)){
break here;
}
if(answer1.equals(Commands.yes)) {
card4 = Math.random() * 12 + 1;
card4 = Math.round(card4);
System.out.println("Your fourth card was a " + card4);
System.out.println("Your cards add up to " + (card1 + card2 + card3 + card4));
total2 = card1 + card2 + card3 + card4;
if(total2 > 21) {
System.out.println("You lose");
break here;
}
break here;
}
}
System.out.println("Your total cards were " + total2);
System.out.println("AI total cards were " + AiTotalcard3);
input.close();
}
}
When you run the program I was hoping that the variables at the top would have new numbers saved into them when the user went through the program. Is there a better way to do this because the console output is always 0 for the total.
First lets look at AiTotalcard3:
It shouldn't always output 0 for that, more precisely it will output 0 in the case where AiCard1 + AiCard2 >= 15, which probably happens a lot.
It makes sense if you trace through your actual code. The first thing that happens is those initializers:
double AiCard1 = 0;
double AiCard2 = 0;
double AiCard3 = 0;
double AiTotalcard3 = AiCard1 + AiCard2 + AiCard3;
So AiTotalcard3 is initially set to 0. It will remain 0 until you change it, which happens here:
AiCard1 = Math.random() * 12 + 1;
AiCard1 = Math.round(AiCard1);
AiCard2 = Math.random() + 12 + 1;
AiCard2 = Math.round(AiCard2);
double AiTotal2cards = AiCard1 + AiCard2;
if(AiTotal2cards < 15) {
AiCard3 = Math.random() * 12 + 1;
AiCard3 = Math.round(AiCard3);
AiTotalcard3 = AiCard1 + AiCard2 + AiCard3;
}
But that only happens if the first two cards add up to less than 15. After that you never touch AiTotalcard3 again.
Your logic can be greatly simplified all around, and also it makes a lot more sense to use int instead of double for the cards, but ignoring all that and sticking to your current style, you could fix this by making sure all paths set AiTotalcard3, for example (again not the cleanest logic but just sticking to your pattern):
if(AiTotal2cards < 15) {
AiCard3 = Math.random() * 12 + 1;
AiCard3 = Math.round(AiCard3);
AiTotalcard3 = AiCard1 + AiCard2 + AiCard3;
} else {
AiTotalcard3 = AiCard1 + AiCard2; // be sure to always set it
}
Now, with all that in mind, you have a similar problem with total2: Not all of your execution paths set the value of total2. It works if you make it up to the 4th card but prior to that you never change it from its initial value of 0. So you're just going to have to go through this with a fine-toothed comb.
One of your fundamental issues is for some reason you're using different variables all over the place for the first 2 cards vs. all the cards. If you just used a single aiTotal and total to accumulate the card totals as you go, you'd avoid most of these issues.
I think your main issue is confusing total and total2. You seem to use both interchangeable in multiple places.
At first, if the user does not pick a third card, total2 will always equal 0 because if the if(answer.equals(Commands.yes)) { is never entered, total2 is never set past the original initialization of 0.
If the user picks a third card but not a fourth, you update the value of total correctly but not total2.
If the user picks a fourth card, then it should work correctly.
Besides the main fixes, here are some tips that you should keep in mind when writing your game:
You mention that the global variables are not recognized, but none of your variables are actually global. You should read up on what exactly that means.
I would suggest using ints or a custom datatype to store card values, as you would never need the decimal places a double provides.
Use loops in your structure to save a lot of code. It will make it cleaner and easier to understand.
Print what the AI is doing. There's no point to having an AI if you can't see its moves.
Anyway, good luck with your game! Programming can be intimidating at first but this is a great start.

Dice Roll Histogram

I have a class question that I cannot seem to understand the logic for.
Modify the program below to print a histogram in which the total number of times the dice rolls equals each possible value is displayed by printing a character like * that number of times, as shown below.
Histogram showing total number of dice rolls for each possible value.
Dice roll histogram:
2: ******
3: ****
4: ***
5: ********
6: *******************
7: *************
8: *************
9: **************
10: ***********
11: *****
12: ****
I do not understand what in the world this histogram is displaying. Its driving me insane and I cannot move forward with my logic if I do not understand what I am doing. I know this question has been asked before but it looks like they all have a specific number of dice roles they are going off of. I am not given a number and this is what is throwing me off. I know this is really a stupid question. But can anyone possibly explain to me what they mean by "Histogram showing total number of dice rolls for each possible value" what is defining this possible value? I am at a total loss... Any help is appreciated. Here is the code I have written so far.
import java.util.Scanner;
import java.util.Random;
public class DiceStats {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
Random randGen = new Random();
int i = 0; // Loop counter iterates numRolls times
int numRolls = 0; // User defined number of rolls
int numOnes = 0; // Tracks number of 1's found
int numTwos = 0; // Tracks number of 2's found
int numThrees = 0; // Tracks number of 3's found
int numFours = 0; // Tracks number of 4's found
int numFives = 0; // Tracks number of 5's found
int numSixes = 0; // Tracks number of 6's found
int numSevens = 0; // Tracks number of 7's found
int numEights = 0; // Tracks number of 8's found
int numNines = 0; // Tracks number of 9's found
int numTens = 0; // Tracks number of 10's found
int numElevens = 0; // Tracks number of 11's found
int numTwelves = 0; // Tracks number of 12's found
int die1 = 0; // Dice values
int die2 = 0; // Dice values
int rollTotal = 0; // Sum of dice values
System.out.println("Enter number of rolls: ");
numRolls = scnr.nextInt();
if (numRolls >= 1) {
// Roll dice numRoll times
for (i = 0; i < numRolls; ++i) {
die1 = randGen.nextInt(6) + 1;
die2 = randGen.nextInt(6) + 1;
rollTotal = die1 + die2;
// Count number of sixes and sevens
if (rollTotal == 1) {
numOnes = numOnes + 1;
}
if (rollTotal == 2) {
numTwos = numTwos + 1;
}
if (rollTotal == 3) {
numThrees = numThrees + 1;
}
if (rollTotal == 4) {
numFours = numFours + 1;
}
if (rollTotal == 5) {
numFives = numFives + 1;
}
if (rollTotal == 6) {
numSixes = numSixes + 1;
}
if (rollTotal == 7) {
numSevens = numSevens + 1;
}
if (rollTotal == 8) {
numEights = numEights + 1;
}
if (rollTotal == 9) {
numNines = numNines + 1;
}
if (rollTotal == 10) {
numTens = numTens + 1;
}
if (rollTotal == 11) {
numElevens = numElevens + 1;
}
else if (rollTotal == 12) {
numTwelves = numTwelves + 1;
}
System.out.println("Roll " + (i+1) + " is " + rollTotal + " (" + die1 +
"+" + die2 + ")");
}
// Prints a histogram of the number of dice rolls
System.out.println("\nDice roll histogram:");
System.out.println("1's: " + numOnes);
System.out.println("2's: " + numTwos);
System.out.println("3's: " + numThrees);
System.out.println("4's: " + numFours);
System.out.println("5's: " + numFives);
System.out.println("6's: " + numSixes);
System.out.println("7's: " + numSevens);
System.out.println("8's: " + numEights);
System.out.println("9's: " + numNines);
System.out.println("10's: " + numTens);
System.out.println("11's: " + numElevens);
System.out.println("12's: " + numTwelves);
}
else {
System.out.println("Invalid rolls. Try again.");
}
return;
}
}
You can see where I entered the entry for histograms. I basically thought that I needed to edit my value given from the integers such as "numOnes" to asterisk but now I'm not certain... any help is appreciated!
EDITED CODE -
System.out.println("\nDice roll histogram:");
System.out.print("2's: ");
for(i = 0; i < numTwos; i++){
System.out.print("*");
}
System.out.println("");
System.out.print("3's: ");
for (i = 0; i < numThrees; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("4's: " );
for (i = 0; i < numFours; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("5's: ");
for (i = 0; i < numFives; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("6's: ");
for (i = 0; i < numSixes; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("7's: ");
for (i = 0; i < numSevens; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("8's: ");
for (i = 0; i < numEights; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("9's: ");
for (i = 0; i < numNines; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("10's: ");
for (i = 0; i < numTens; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("11's: ");
for (i = 0; i < numElevens; i++);{
System.out.print("*");
}
System.out.println("");
System.out.print("12's: ");
for (i = 0; i < numTwelves; i++);{
System.out.print("*");
}
System.out.println("");
}
OUTPUTS -
Enter number of rolls:
5
Roll 1 is 8 (2+6)
Roll 2 is 9 (6+3)
Roll 3 is 9 (5+4)
Roll 4 is 6 (4+2)
Roll 5 is 9 (6+3)
Dice roll histogram:
2's:
3's: *
4's: *
5's: *
6's: *
7's: *
8's: *
9's: *
10's: *
11's: *
12's: *
I can enter a larger number of rolls and I will get an asterisk for the 2's and it will increase like I need but it will not increase the rest of the numbers and they all only get one asterisk. What is keeping my code from properly increasing the amount of *'s? Iv been fighting with this for hours :/
"I do not understand what in the world this histogram is displaying."
Well, as you said:
"Histogram showing total number of dice rolls for each possible value"
The histogram:
2: ******
3: ****
4: ***
5: ********
6: *******************
7: *************
8: *************
9: **************
10: ***********
11: *****
12: ****
is a record of the rolls of a pair of six sided dice. The possible values of totaling a pair of dice range from 2 to 12. If you rolled them 100 times they might give these results.
This histogram shows that the value 6 was most frequently rolled (19 times) and 4 the least frequently rolled (3 times). If you counted up every * you'd know how many times the dice have been rolled.
You may think that a histogram must look like this:
But turn that sideways:
and imagine that the blue bars are *'s, the 100 - 150 label is a 2, and the 150 - 200 label is a 3, well then it starts to look like your histogram.
Either form is a histogram. They let you compare quantities (how many) of things that fall in different categories (kinds) of things.
A graphic chart is difficult to output from a program that is text based so instead it's asking you to display what is basicly ascii art:
If this was in a text file, and not program output, this could also be considered a form of tally. You can easily add new *'s as you receive new data. It's the same trick as this:
Hope that makes more sense.
SPOILER ALERT: If that helped and you'd like to take a crack at modifying the program yourself read no further. Otherwise...
This
System.out.println("\nDice roll histogram:");
System.out.println(" 1's: " + nManyStars(numOnes));
System.out.println(" 2's: " + nManyStars(numTwos));
System.out.println(" 3's: " + nManyStars(numThrees));
System.out.println(" 4's: " + nManyStars(numFours));
System.out.println(" 5's: " + nManyStars(numFives));
System.out.println(" 6's: " + nManyStars(numSixes));
System.out.println(" 7's: " + nManyStars(numSevens));
System.out.println(" 8's: " + nManyStars(numEights));
System.out.println(" 9's: " + nManyStars(numNines));
System.out.println("10's: " + nManyStars(numTens));
System.out.println("11's: " + nManyStars(numElevens));
System.out.println("12's: " + nManyStars(numTwelves));
and this
static String nManyStarsOld(int n) {
String result = "";
for (int i = 0; i < n; i++) {
result += "*";
}
return result;
}
should, if dropped in the right places, get your program to stop printing what it prints now which is this:
Enter number of rolls:
20
Roll 1 is 5 (2+3)
Roll 2 is 10 (4+6)
Roll 3 is 7 (5+2)
Roll 4 is 7 (5+2)
Roll 5 is 5 (1+4)
Roll 6 is 11 (6+5)
Roll 7 is 8 (3+5)
Roll 8 is 8 (2+6)
Roll 9 is 7 (1+6)
Roll 10 is 8 (3+5)
Roll 11 is 12 (6+6)
Roll 12 is 6 (2+4)
Roll 13 is 8 (6+2)
Roll 14 is 8 (4+4)
Roll 15 is 7 (1+6)
Roll 16 is 4 (2+2)
Roll 17 is 6 (5+1)
Roll 18 is 7 (6+1)
Roll 19 is 6 (1+5)
Roll 20 is 5 (1+4)
Dice roll histogram:
1's: 0
2's: 0
3's: 0
4's: 1
5's: 3
6's: 3
7's: 5
8's: 5
9's: 0
10's: 1
11's: 1
12's: 1
And instead, get it to print this:
Dice roll histogram:
1's:
2's:
3's:
4's: *
5's: ***
6's: ***
7's: *****
8's: *****
9's:
10's: *
11's: *
12's: *
Next time you post a question please include the current output along with the expected output.
If you feel like being a smarty pants there is actually a one line version of nManyStars():
static String nManyStars(int n) {
return new String(new char[n]).replace("\0", "*");
}
Inspired by this: https://stackoverflow.com/a/4903603/1493294
Also, if you have at least Java 11 you can trade in nManyStars(n) for "*".repeat(n)
Hope it helps
Iv got it all working. Thank you #CandiedOrange and #MadProgrammer for the help and guidance! Found that my histogram code was messed up with my for statements having a ; in an incorrect spot causing my for statement to not apply the * based on its process of running through the for statement and it was just printing a * as a normal print function. All is well. Thanks for all the help!

Need assistance with Min and Max function?

I have an application a number guess game, users have to guess a number between 0 and 100, when they guess right the program asks them if they would like to play again when their done play I display the least number of guesses in a game and the greatest number of guess in a game. Right now all i get is the sum of all their guesses in the when using the "Math.min(,)"?
How do I get the minimum function to work??? the function code is in further below.
leastNumGuesses = Math.min(leastNumGuesses,guesses);
double rightNum = Math.random() *100;
int randomNum = (int) rightNum; //convert the random number to int
int tries = 0; //single game gussess output
int numberOfGames = 0;
int allTries = 0; //accumalates all tries(sum of all tries)
int guesses = 0; // guesses of all games combined
int gameGuesses = 0;
int leastNumGuesses = 100;
int mostNumGuesses = 0;
while (choice.equalsIgnoreCase("y"))
{
System.out.println();
int guess = getIntWithinRange(sc,"Enter the Number: ", 0, 100);
tries++;
guesses++;
gameGuesses++;
if (guess == randomNum)
{
numberOfGames++;
System.out.println("You got it in " + tries + " tries.");
leastNumGuesses = Math.min(leastNumGuesses,gameGuesses);
if (tries <=3)
System.out.println("Great work! You are a mathematical wizard.");
else if (tries > 3 && tries <= 7)
System.out.println("Not too bad! You've got some potential.");
else if (tries > 7)
System.out.println("What took you so long? Maybe you should take some lessons.");
System.out.println();
System.out.println("Would you like to play again (y/n):");
choice = sc.nextLine();
while (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y"))
{
System.out.println("Error! entry must be \"y\" or \"n\".");
System.out.println("Would you like to play again (y/n):");
choice = sc.nextLine();
}
if (choice.equalsIgnoreCase("y"))
{ // reset the random number & tries
rightNum = Math.random() *100;
randomNum = (int) rightNum;
tries=0;
gameGuesses++;
}
else if (choice.equalsIgnoreCase("n"))
{
allTries += guesses;
int averageNumGuess = allTries / numberOfGames;
System.out.println("Bye - Come back again");
System.out.println("Number of Games Played: " + numberOfGames);
System.out.println("Average Number of Guesses: " + averageNumGuess);
System.out.println("Least Amount of Guesses In a Single Game: " + leastNumGuesses);
}
}
It seems that you're changing what you want guesses to stand for in the middle of the program.
Remember that guesses is the total number of guesses over all games played, and that leastNumGuesses is initially set to 100. In most cases, you will find that guesses < leastNumGuesses, and thus the Math.min(guesses, leastNumGuesses) function will return guesses.
To fix: use variable other than guesses, for example, gameGuesses to keep track of how many guesses were made in a game. Then, Math.min(,) will behave as you expect.

Categories