Variable is not properly transferring over to method [duplicate] - java

This question already has answers here:
How do I get the variable of one method to be a variable in another method for Java?
(4 answers)
Closed 8 years ago.
I'm trying to take the output of another method and use it in another method. I know there are other questions that are similar to mine but the solutions that were in those questions never solved my problem, though they did help a little. Here's where I'm stuck (problem is at rewardBet() method):
class Player {
private ArrayList<Card>hand;
private double cash, bet;
//double cash, bet;
public Player(double theCash)
{
cash = theCash;
hand = new ArrayList<Card>();
bet = 0;
}
public double wagerBet()
{
Scanner in = new Scanner(System.in);
System.out.print("Wager a bet: ");
double bet = in.nextDouble();
cash = cash - bet;
System.out.println("You wagered " + bet + ". " + "Now you have " + cash + " cash left.");
return bet;
}
public void rewardBet()
{
bet = wagerBet(); //this is supposed to be taking whatever the user wagered as a bet in the previous method and
cash = cash + (bet * 2); // apply it to this formula in order to mutate the total cash the player has
System.out.println("You now have " + cash + "cash.");
}
Any suggestions as to how to get this bet variable input to carry over?
EDIT, here's the main method like you guys requested:
class BlackJack {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
Deck myDeck = new Deck();
myDeck.shuffle();
Player me = new Player(1000);
Player dealer = new Player(0);
Card c = myDeck.dealCard();
me.wagerBet();
System.out.println("Your first card is " + c);
me.hit(c);
c = myDeck.dealCard();
System.out.println("Your next card is " + c);
me.hit(c);
c = myDeck.dealCard();
System.out.println("Your total hand is currently " + me.totalHand() + ".");
System.out.println("Dealer showing " + c);
dealer.hit(c);
c = myDeck.dealCard();
String answer;
System.out.print("Hit or Stay?");
answer = in.nextLine();
while(answer.equals("Hit") || answer.equals("hit"))
{
System.out.println("Your next card is " + c);
me.hit(c);
c = myDeck.dealCard();
System.out.println("Your total hand is currently " + me.totalHand() + ".");
if(me.totalHand() == 21)
{
System.out.println("You win");
me.rewardBet();
System.exit(0);
}
else if(me.totalHand() < 21)
{
System.out.print("Hit or Stay?");
answer = in.nextLine();
}
else{
System.out.println("Player bust.");
System.exit(0);
}}
while(dealer.totalHand() < 17)
{
System.out.println("Dealer draws " + c);
dealer.hit(c);
c = myDeck.dealCard();
System.out.println("Dealer's total hand is currently " + dealer.totalHand() + ".");
if(dealer.totalHand() == 21)
{
System.out.println("Dealer wins.");
System.exit(0);
}
else if(dealer.totalHand() > 21)
{
System.out.println("Dealer bust. You win.");
me.rewardBet();
System.exit(0);
}
}
if(me.totalHand() > dealer.totalHand())
System.out.println("You win!");
me.rewardBet();
if(me.totalHand() < dealer.totalHand())
System.out.println("Loooooser");
if(me.totalHand() == dealer.totalHand())
System.out.println("Push. Nobody wins");
}
}
and to clarify my problem, the wagerBet() method asks for a double input from the user in the form of a bet. If the player wins his hand then the rewardBet() method will reward the player, giving him back the amount he bet plus the reward, hence 'bet * 2'. The problem is the rewardBet() method isn't recognizing the 'bet' input at all, I'm trying to figure out how to make it so. So for example I make a bet of 50, so now I have 950 dollars (1000 is default). I win the round so rewardBet() needs to give me 100 dollars. Right now it isn't giving me anything for winning.

Well, one problem is at the very last line of your main method:
if(me.totalHand() > dealer.totalHand())
System.out.println("You win!");
me.rewardBet();
You need to wrap this body in braces - the if statement if only functioning on the print statement. Although this doesn't seem as though it will fix the problem that you've described.
Perhaps you should consider doing a different design altogether, and avoid using so much duplicate code.
BlackJack:
public class BlackJack
{
private Deck deck;
private Player me;
private Player dealer;
public static void main(String[] args)
{
BlackJack game = new BlackJack();
game.run();
}
public BlackJack()
{
deck = new Deck();
deck.shuffle();
me = new Player("Joe", 1000.0);
dealer = new Player("Dealer", 0);
}
public void run()
{
double bet = requestBet(me);
// Deal your first two cards
dealNextCard(me, "Your first card is ");
dealNextCard(me, "Your second card is ");
me.printHandTotal();
// Deal dealer's first card
dealNextCard(dealer, "Dealer showing ");
while(requestHitOrStay())
{
dealNextCard(me, "Your next card is ");
me.printHandTotal();
if(me.totalHand() == 21)
{
System.out.println(me.getName() + " wins!");
rewardBet(me, bet);
System.exit(0);
}
else if(me.totalHand() > 21)
{
System.out.println(me.getName() + " bust!");
System.exit(0);
}
}
while(dealer.totalHand() < 17)
{
dealNextCard(dealer, "Dealer draws ");
dealer.printHandTotal();
if(dealer.totalHand() == 21)
{
System.out.println(dealer.getName() + " wins!");
System.exit(0);
}
else if(dealer.totalHand() > 21)
{
System.out.println(dealer.getName() + " bust. You win!");
rewardBet(me, bet);
System.exit(0);
}
}
if(me.totalHand() > dealer.totalHand())
{
System.out.println("You win!");
rewardBet(me, bet);
}
else if(me.totalHand() < dealer.totalHand())
{
System.out.println("Loooooser");
}
else
{
System.out.println("Push. Nobody wins");
}
}
public boolean requestHitOrStay()
{
System.out.print("Hit or Stay? ");
Scanner in = new Scanner(System.in);
return in.nextLine().toLowerCase().equals("hit");
}
public void dealNextCard(Player p, String prefix)
{
Card c = deck.dealCard();
System.out.println(prefix + c);
p.addCard(c);
}
public double requestBet(Player p)
{
Scanner in = new Scanner(System.in);
double bet = Integer.MAX_VALUE;
while(bet > p.getCash())
{
System.out.print("Wager a bet: ");
bet = in.nextDouble();
}
p.setCash(p.getCash() - bet);
System.out.println(p.getName() + " wagered " + bet + ". " + "Now they have " + p.getCash() + " cash left.");
return bet;
}
public void rewardBet(Player p, double bet)
{
p.setCash(p.getCash() + bet * 2);
System.out.println(p.getName() + " now has " + p.getCash() + " cash.");
}
}
Player:
public class Player
{
private ArrayList<Card> hand;
private double cash;
private String name;
public Player(String playerName, double startingCash)
{
hand = new ArrayList<Card>();
cash = startingCash;
name = playerName;
}
public void addCard(Card c)
{
hand.add(c);
}
public int totalHand()
{
int total = 0;
for(Card c : hand)
{
total += c.getValue();
}
return total;
}
public void printHandTotal()
{
System.out.println(name + "'s' total hand is currently " + totalHand() + ".");
}
public String getName()
{
return name;
}
public double getCash()
{
return cash;
}
public void setCash(double cash)
{
this.cash = cash;
}
}

Related

Throws Exception when trying to break loop because a condition has been met

I am trying to figure out why I cannot get the loop to break if either "n" is input for playAgain or when the total is below $10. If you see how I can break the loop to run the gameOver function without having an exception thrown that would be a great help. I have noted in the code below that I am having trouble with. I am unsure why this exception is being thrown. If you are able to find out how to break the loop when total is less than 10 or when playAgain is false please let me know!
import java.util.Random;
import java.util.Scanner;
public class GameOfCrapsTester {
static Scanner in = new Scanner(System.in);
static Random rand = new Random();
public static void main(String[] args) {
System.out.println("Welcome to the game of Craps");
System.out.println(" ");
System.out.println("The house has given you a starting balance of $500");
System.out.println("On each round, you will make a whole number wager.");
System.out.println("The minimum wager is $10, and the maximum wager is your remaining balance.");
System.out.println(" ");
System.out.println("You may keep playing until you decide to cash in, or");
System.out.println(" you can't cover the minimum wager.");
System.out.println("Good Luck!");
boolean win;
double wins = 0, numOfGames = 0;
int total = 500;
// Come out roll and set point value
int pointValue = 0;
boolean playAgain = true;
while (playAgain && total > 0)
{
System.out.println(" ");
System.out.println("Your balance is $" + total);
System.out.println(" ");
System.out.println("Place your bet: $");
// Get and check wager placed
int bet = in.nextInt();
while (bet > total || bet < 10)
{
if (bet < 10)
{
System.out.println("Bet must be larger than $10.");
}
System.out.println("I'm sorry, that's not a valid wager; please re-enter: ");
bet = in.nextInt();
}
int num = rollDice();
if ((num >= 4 && num <= 10 && num != 7) || num == 0)
{
pointValue = num;
System.out.println(" ");
System.out.println("Your point value is " + pointValue);
System.out.println(" ");
win = rollWithPoint(pointValue);
if (win)
{
total = wonGame(bet, total);
wins++;
numOfGames++;
System.out.println("Wins: " + wins + " Number of games: " + numOfGames);
}
else if (!win)
{
total = lostGame(bet, total);
numOfGames++;
System.out.println("Wins: " + wins + " Number of games: " + numOfGames);
}
}
else if (num == 7 || num == 11)
{
total = wonGame(bet, total);
wins++;
numOfGames++;
System.out.println("Wins: " + wins + " Number of games: " + numOfGames);
}
else
{
total = lostGame(bet, total);
numOfGames++;
System.out.println("Wins: " + wins + " Number of games: " + numOfGames);
}
if (total <= 9) // THIS IS WHERE I AM HAVING TROUBLE
{
break;
}
System.out.println("Keep playing (y/Y or n/N)? ");
in.nextLine();
String again = in.nextLine();
if (again.equalsIgnoreCase("y"))
{
playAgain = true;
}
else if (again.equalsIgnoreCase("n")) // THIS IS WHERE I AM HAVING TROUBLE
{
break;
}
else
{
System.out.println("Invalid character input, try again:");
again = in.nextLine();
}
}// end of loop
gameOver(wins, numOfGames);
} // END of main
public static int rollDice() {
int dice1, dice2, total;
dice1 = rand.nextInt(6) + 1;
dice2 = rand.nextInt(6) + 1;
total = dice1 + dice2;
System.out.print("Your roll: ");
System.out.print("Dice1: " + dice1);
System.out.print(", Dice2: " + dice2);
System.out.println("; Roll Value: " + total);
return total;
} // END of rollDice
public static boolean rollWithPoint(int point) {
int total = rollDice();
boolean winner = false;
while(total != 7 && winner == false)
{
total = rollDice();
if (total == point)
{
winner = true;
}
else
{
winner = false;
}
}
return winner;
} // END of rollWithPoint
public static int lostGame(int bet, int total) {
System.out.println("Oh, I'm sorry, you lost.");
System.out.println(" ");
total = total - bet;
System.out.println("Your current balance: $" + total);
System.out.println(" ");
return total;
} // END of lostGame
public static int wonGame(int bet, int total) {
System.out.println("A winner!");
System.out.println(" ");
total = total + bet;
System.out.println("Your current balance: $" + total);
System.out.println(" ");
return total;
} // END of wonGame
public static void gameOver(double win, double tot) {
double winPercent = (win / tot) * 100;
System.out.println(" ");
System.out.printf("Based on your play, the probability of winning is %.2%", winPercent);
System.out.println(" ");
System.out.println("Seems you lost your shirt; better luck next time.");
System.out.println("Have a nice day! Hope to see you soon!");
} // END of gameOver
} // END of GameOfCraps
There is no error when you change this (without using String.format()):
System.out.printf("Based on your play, the probability of winning is %.2%", winPercent);
To this:
System.out.println("Based on your play, the probability of winning is " + winPercent + "%.");
Example with a little bet (console):
Your balance is $11
Place your bet: $
10
Your roll: Dice1: 1, Dice2: 2; Roll Value: 3
Oh, I'm sorry, you lost.
Your current balance: $1
Wins: 0.0 Number of games: 2.0
Based on your play, the probability of winning is 0.0%.
Seems you lost your shirt; better luck next time.
Have a nice day! Hope to see you soon!
I cannot get the loop to break if either "n" is input for playAgain or
when the total is below $10.
It works fine too. If I put a bet below 10 it asks me to put another bit. What

Can't get my code to repeat the questions for the game to continue

I have to write a code for my class I'm taking. It is a game based on betting on 2 colors and numbers from 1 - 36. The user has a set amount of chips already given to them which is 100. I have already written most of the code, however, I can't get my code to repeat the process. I am currently using a Do-While loop. but it just isn't working.
Here is my code:
import java.util.Scanner;
import java.lang.Math;
public class Program_8 {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int chipsNow = 100;
int userChoice;
int chipsBetted = 0;
//welcome message
welcome();
do {
int spinNum = (int)(Math.random() * 36) + 0;
userChoice = getMenuChoice(userInput);
//get user choice
if (userChoice == 1) {
int getNum = getNumber(userInput);
int getBet = getBet(userInput, chipsNow);
String determineColor = determineColor(spinNum);
System.out.println("\nSpinning Wheel....");
System.out.println("Spin Number: " + spinNum);
System.out.println("Spin Color: " + determineColor);
if (getNum == spinNum) {
chipsNow += getBet;
chipsBetted += getBet;
System.out.println("Congrats, you won!");
System.out.println("\nYou now have: " + chipsNow + " chips");
;
}
else {
chipsNow -= getBet;
System.out.println("\nSorry, you lost!");
System.out.println("You now have: " + chipsNow + " chips");
}
}
if (userChoice == 2) {
String getColor = getColor(userInput);
int getBet = getBet(userInput, chipsNow);
String determineColor = determineColor(spinNum);
System.out.println("Spinning Wheel....");
System.out.println("Spin Number: " + spinNum);
System.out.println("Spin Color: " + determineColor);
if (getColor.equals(determineColor)) {
chipsNow += getBet;
chipsBetted += getBet;
System.out.println("\nCongrats, you won!");
System.out.println("You now have: " + chipsNow + " chips");
}
else {
chipsNow -= getBet;
System.out.println("\nSorry, you lost!");
System.out.println("You now have: " + chipsNow + " chips");
}
}
}while (userChoice != 3 && chipsNow > 0);
}
//welcome message
public static void welcome() {
int chipsNow = 100;
System.out.println("############################");
System.out.println("# Welcome To Roulette #");
System.out.println("############################");
System.out.println("# Number Bets Payout: 35:1 #");
System.out.println("# Color Bets Payout: 1:1 #");
System.out.println("############################\n");
System.out.println("Chips owned: " + chipsNow + "\n");
System.out.println("1. Pick a number to bet on");
System.out.println("2. Pick a color to bet on");
System.out.println("3. Cash Out\n");
}
//get menu choice
public static int getMenuChoice(Scanner userInput) {
int getMenuChoice;
System.out.println("\nChoose an option [1-3]: ");
getMenuChoice = userInput.nextInt();
return getMenuChoice;
}
public static int getNumber(Scanner userInput) {
int getNumber;
do {
System.out.println("Enter a number to bet on [0-36]: ");
getNumber = userInput.nextInt();
}while (getNumber < 0 || getNumber > 36);
return getNumber;
}
public static String getColor(Scanner userInput) {
String getColor = "";
do{
System.out.println("Enter a color to bet on [Red or Black]: ");
getColor = userInput.next();
}while (!(getColor.equals("Red") || getColor.equals("Black")));
return getColor;
}
public static int getBet(Scanner userInput, int chipsNow) {
int getBet;
do{
System.out.println("Enter the number of chips to bet [1 - " + chipsNow + "]: ");
getBet = userInput.nextInt();
}while (getBet < 1 || getBet > chipsNow);
return getBet;
}
public static String determineColor(int spinNum) {
if (spinNum % 2 == 0) {
if (spinNum == 0) {
return "Green";
}
//even
else {
return "Red";
}
}
return "Black";
}
public static void report(int chipsNow) {
System.out.println("\nThanks for Playing!");
System.out.println("You Won a total of: " + chipsNow + " chips today");
}
}
So just looking at the code I'd:
Declare int userChoice = 0; outside the do while. This is needed for the while condition to work.
welcome(); and userChoice = getMenuChoice(userInput); should move into the do while thus it will repeat the welcome message and ask for a user choice everything the do while executes
Simplify your while loop like this while(userChoice != 3 && chipsNow > 0). This is just to make it more readable.
Lastly remove the break;s in your if(getNum == spinNum) { } else { }. A break will force the while loop to be exited regardless of whether the while condition is met. So basically if you win or lose a game your loop will exit, which I don't think is what you want. You only want the loop to exit if the chipsNow < 0 or the userChoice == 3

Trouble with Getters and Setters [Java]

I am fairly new to java (my first college course for it) and with everything being online, I'm having a hard time understanding things - so I apologize if this is stupid or obvious. In this project, I have two classes named "Basketball" and "BasketballDemo". I am using a variety of methods to keep the score of a game between two basketball teams. The methods used are all in 'Basketball', while a 'while loop' lives in the other method (BasketballDemo) to keep running the methods when specified until the game ends. I am trying to use 'getters' and 'setters' to transfer the values between the two, but I am severely confused - no matter what I do, the values in 'BasketballDemo' are always 0 after running no matter how I slice it. I have done a profuse amount of research on how exactly it works, but my head is having a very hard time with what I'm sure for many is an easy subject. I apologize in advance for the brevity of this code - because I don't know where the issue is I don't know exactly where in the code the problem is situated. Here are the two classes:
Basketball.java:
import java.util.Scanner;
public class Basketball {
private final String teamOne = "Lions";
private final String teamTwo = "Bears";
private int teamOneScore = 0;
private int teamTwoScore = 0;
private String gameState = "ongoing";
public int scoreOnePoint(String whatTeam) {
if (whatTeam.equalsIgnoreCase("Lions")) {
Basketball newScore = new Basketball();
newScore.setTeamOneScore(newScore.getTeamOneScore() + 1);
System.out.println("The Lions' score is now: " + newScore.getTeamOneScore() + ".");
return newScore.getTeamOneScore();
}
else if (whatTeam.equalsIgnoreCase("Bears")) {
Basketball newScore = new Basketball();
newScore.setTeamTwoScore(newScore.getTeamTwoScore() + 1);
System.out.println("The Lions' score is now: " + newScore.getTeamTwoScore() + ".");
return newScore.getTeamTwoScore();
}
else {
System.out.println("ERROR: Entered invalid team name. Please try again.");
return 0;
}
}
public int scoreTwoPoints(String whatTeam) {
if (whatTeam.equalsIgnoreCase("Lions")) {
Basketball newScore = new Basketball();
newScore.setTeamOneScore(newScore.getTeamOneScore() + 2);
System.out.println("The Lions' score is now: " + newScore.getTeamOneScore() + ".");
return newScore.getTeamOneScore();
}
else if (whatTeam.equalsIgnoreCase("Bears")) {
Basketball newScore = new Basketball();
newScore.setTeamTwoScore(newScore.getTeamTwoScore() + 2);
System.out.println("The Lions' score is now: " + newScore.getTeamTwoScore() + ".");
return newScore.getTeamTwoScore();
}
else {
System.out.println("ERROR: Entered invalid team name. Please try again.");
return 0;
}
}
public int scoreThreePoints(String whatTeam) {
if (whatTeam.equalsIgnoreCase("Lions")) {
Basketball newScore = new Basketball();
newScore.setTeamOneScore(newScore.getTeamOneScore() + 3);
System.out.println("The Lions' score is now: " + newScore.getTeamOneScore() + ".");
return newScore.getTeamOneScore();
}
else if (whatTeam.equalsIgnoreCase("Bears")) {
Basketball newScore = new Basketball();
newScore.setTeamTwoScore(newScore.getTeamTwoScore() + 3);
System.out.println("The Bears' score is now: " + newScore.getTeamTwoScore() + ".");
return newScore.getTeamTwoScore();
}
else {
System.out.println("ERROR: Entered invalid team name. Please try again.");
return 0;
}
}
public void finished() {
Scanner isFinished = new Scanner(System.in);
System.out.println("Are you sure the game finished? (Y/N):");
String finished = isFinished.nextLine();
if (finished.equalsIgnoreCase("Y")) {
Basketball isFinishedNow = new Basketball();
isFinishedNow.setGameState(finished);
if (isFinishedNow.getTeamOneScore() > isFinishedNow.getTeamTwoScore()) {
System.out.println("The Lions win!");
}
else if (isFinishedNow.getTeamOneScore() < isFinishedNow.getTeamTwoScore()) {
System.out.println("The Bears win!");
}
else {
System.out.println("It's a tie!");
}
System.out.println("The game is finished!");
}
else {
System.out.println("We aren't done here yet!");
}
}
public int scoreCheck(String whatTeam) {
if (whatTeam.equalsIgnoreCase("Lions")) {
Basketball checkScore = new Basketball();
System.out.println("The Lions are currently at " + checkScore.getTeamOneScore() + " points.");
return checkScore.getTeamOneScore();
}
else if (whatTeam.equalsIgnoreCase("Bears")) {
Basketball checkScore = new Basketball();
System.out.println("The Bears are currently at " + checkScore.getTeamTwoScore() + " points.");
return checkScore.getTeamTwoScore();
}
else {
System.out.println("ERROR: You entered an invalid team name, please try again.");
return 0;
}
}
public void winningTeam() {
Basketball whoIsWinning = new Basketball();
if (whoIsWinning.getTeamOneScore() > whoIsWinning.getTeamTwoScore()) {
System.out.println("The Lions are winning!");
}
else if (whoIsWinning.getTeamOneScore() < whoIsWinning.getTeamTwoScore()) {
System.out.println("The Bears are winning!");
}
else {
System.out.println("It's currently a tie!");
}
}
public int getTeamOneScore() {
return teamOneScore;
}
public void setTeamOneScore(int newScore) {
this.teamOneScore = newScore;
}
public int getTeamTwoScore() {
return teamTwoScore;
}
public void setTeamTwoScore(int newScore) {
this.teamTwoScore = newScore;
}
public String getGameState() {
return gameState;
}
public void setGameState(String newGameState) {
this.gameState = newGameState;
}
public static void main(String[] args) {
}
}
BasketBallDemo.java:
import java.util.Scanner;
public class BasketballDemo {
public static void main(String[] args) {
Basketball game = new Basketball();
while (game.getGameState() == "ongoing") {
Scanner getUpdateOne = new Scanner(System.in);
System.out.println("Enter the team that scored, or 'finished' if the game is over: ");
String gameUpdateOne = getUpdateOne.nextLine();
Scanner getUpdateTwo = new Scanner(System.in);
System.out.println("Enter the amount scored (1/2/3): ");
int gameUpdateTwo = getUpdateTwo.nextInt();
if (gameUpdateOne.equalsIgnoreCase("Finished")) {
game.finished();
}
else if (gameUpdateOne.equalsIgnoreCase("Lions")) {
if (gameUpdateTwo == 1) {
game.scoreOnePoint("Lions");
game.scoreCheck("Lions");
game.scoreCheck("Bears");
game.winningTeam();
}
else if (gameUpdateTwo == 2) {
game.scoreTwoPoints("Lions");
game.scoreCheck("Lions");
game.scoreCheck("Bears");
game.winningTeam();
}
else if (gameUpdateTwo == 3) {
game.scoreThreePoints("Lions");
game.scoreCheck("Lions");
game.scoreCheck("Bears");
game.winningTeam();
}
}
else if (gameUpdateOne.equalsIgnoreCase("Bears")) {
if (gameUpdateTwo == 1) {
game.scoreOnePoint("Bears");
game.scoreCheck("Lions");
game.scoreCheck("Bears");;
game.winningTeam();
}
else if (gameUpdateTwo == 2) {
game.scoreTwoPoints("Bears");
game.scoreCheck("Lions");
game.scoreCheck("Bears");
game.winningTeam();
}
else if (gameUpdateTwo == 3) {
game.scoreThreePoints("Bears");
game.scoreCheck("Lions");
game.scoreCheck("Bears");
game.winningTeam();
}
}
else {
System.out.println("ERROR: invalid entry, please try again.");
}
}
}
}
TLDR;
You have a couple issues, both of which are in Basketball. You call winningTeam after every update in BasketballDemo. Currently, this creates a new instance of Basketball, which means all your class variables are going to be 0, or whatever your initial value is. You also create new instances of Basketball in your scoring methods. See below for details.
Change:
public void winningTeam() {
//You are creating a new instance of Basketball.
Basketball whoIsWinning = new Basketball();
if (whoIsWinning.getTeamOneScore() > whoIsWinning.getTeamTwoScore()) {
System.out.println("The Lions are winning!");
}
else if (whoIsWinning.getTeamOneScore() < whoIsWinning.getTeamTwoScore()) {
System.out.println("The Bears are winning!");
}
else {
System.out.println("It's currently a tie!");
}
}
It should be this:
public void winningTeam() {
//You want to check the current instance of Basketball
if (this.getTeamOneScore() > this.getTeamTwoScore()) {
System.out.println("The Lions are winning!");
}
else if (this.getTeamOneScore() < this.getTeamTwoScore()) {
System.out.println("The Bears are winning!");
}
else {
System.out.println("It's currently a tie!");
}
}
Also, you are creating a new instance of Basketball when you score:
public int scoreOnePoint(String whatTeam) {
if (whatTeam.equalsIgnoreCase("Lions")) {
Basketball newScore = new Basketball();
newScore.setTeamOneScore(newScore.getTeamOneScore() + 1);
System.out.println("The Lions' score is now: " + newScore.getTeamOneScore() + ".");
return newScore.getTeamOneScore();
}
else if (whatTeam.equalsIgnoreCase("Bears")) {
Basketball newScore = new Basketball();
newScore.setTeamTwoScore(newScore.getTeamTwoScore() + 1);
System.out.println("The Lions' score is now: " + newScore.getTeamTwoScore() + ".");
return newScore.getTeamTwoScore();
}
else {
System.out.println("ERROR: Entered invalid team name. Please try again.");
return 0;
}
}
You want something more like this:
public int scoreOnePoint(String whatTeam) {
if (whatTeam.equalsIgnoreCase("Lions")) {
this.setTeamOneScore(this.getTeamOneScore() + 1);
System.out.println("The Lions' score is now: " + newScore.getTeamOneScore() + ".");
return this.getTeamOneScore();
}
else if (whatTeam.equalsIgnoreCase("Bears")) {
this.setTeamTwoScore(this.getTeamTwoScore() + 1);
System.out.println("The Lions' score is now: " + newScore.getTeamTwoScore() + ".");
return this.getTeamTwoScore();
}
else {
System.out.println("ERROR: Entered invalid team name. Please try again.");
return 0;
}
}
Make sure you update all your scoring methods to do something similar to what is above.
Side note:
You don't need Main in BasketBall. You can remove this in Basketball:
public static void main(String[] args) {
}
The problem is you are creating the new Basketball object in the methods of Basketball class. You should be traversing the single game object which is crated in the main method of BasketballDemo. Here is the example
Basketball.java
public int scoreOnePoint(Basketball game, String whatTeam) {
if (whatTeam.equalsIgnoreCase("Lions")) {
game.setTeamOneScore(newScore.getTeamOneScore() + 1);
System.out.println("The Lions' score is now: " + game.getTeamOneScore() + ".");
return game.getTeamOneScore();
}
else if (whatTeam.equalsIgnoreCase("Bears")) {
game.setTeamTwoScore(newScore.getTeamTwoScore() + 1);
System.out.println("The Lions' score is now: " + game.getTeamTwoScore() + ".");
return game.getTeamTwoScore();
}
else {
System.out.println("ERROR: Entered invalid team name. Please try again.");
return 0;
}
}
Update other methods in similar way and in main method pass the same game object every time.
This is not the best design but you will get a clue.
I took the liberty to address some code quality issues and significantly simplify the logic. It felt like there were a few areas that the logic to error handle was repeated along with the setting of scoring. The issues mentioned by the other answers have also been fixed most notably, handling of the objects and not recreating a new object every time we need to use it. I have attached the refactored code below. Do reach out with any doubts or clarifications.
Basketball.java
package stackoverflow;
import java.util.Scanner;
public class Basketball {
private final String teamOne;
private final String teamTwo;
private int teamOneScore = 0;
private int teamTwoScore = 0;
private String gameState = "ongoing";
public Basketball(String teamOne, String teamTwo) {
this.teamOne = teamOne;
this.teamTwo = teamTwo;
}
public void finished() {
Scanner isFinished = new Scanner(System.in);
System.out.println("Are you sure the game finished? (Y/N):");
String finished = isFinished.nextLine();
if (finished.equalsIgnoreCase("Y")) {
setGameState(finished);
if (getTeamOneScore() > getTeamTwoScore()) {
System.out.println("The " + teamOne + " win!");
}
else if (getTeamOneScore() < getTeamTwoScore()) {
System.out.println("The" + teamTwo + " win!");
}
else {
System.out.println("It's a tie!");
}
System.out.println("The game is finished!");
} else {
System.out.println("We aren't done here yet!");
}
}
public void winningTeam() {
if (teamOneScore > teamTwoScore) {
System.out.println("The " + teamOne + " are winning!");
}
else if (teamOneScore < teamTwoScore) {
System.out.println("The " + teamTwo + " are winning!");
}
else {
System.out.println("It's currently a tie!");
}
}
public int getTeamOneScore() {
return teamOneScore;
}
public void setTeamOneScore(int newScore) {
System.out.println("The Bears score is now: " + newScore + ".");
this.teamOneScore = newScore;
}
public int getTeamTwoScore() {
return teamTwoScore;
}
public void setTeamTwoScore(int newScore) {
System.out.println("The Lions score is now: " + newScore + ".");
this.teamTwoScore = newScore;
}
public String getGameState() {
return gameState;
}
public void setGameState(String newGameState) {
this.gameState = newGameState;
}
}
BasketballDemo.java
package stackoverflow;
import java.util.Scanner;
public class BasketballDemo {
private static final String BEARS = "bears";
private static final String LIONS = "lions";
private static final String FINISHED = "finished";
public static void main(String[] args) {
Basketball game = new Basketball("Bears", "Lions");
while (game.getGameState().equals("ongoing")) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the team that scored, or 'finished' if the game is over: ");
String team = scanner.nextLine().toLowerCase();
System.out.println("Enter the amount scored (1/2/3): ");
int score = scanner.nextInt();
switch(team) {
case(FINISHED):
game.finished();
break;
case(BEARS):
game.setTeamOneScore(game.getTeamOneScore() + score);
game.winningTeam();
break;
case(LIONS):
game.setTeamTwoScore(game.getTeamTwoScore() + score);
game.winningTeam();
break;
default:
System.out.println("ERROR: invalid entry, please try again.");
break;
}
}
}
}

while loop if statements

I've almost got this thing working, I just can't manage to get the:
if((pscore <= card1 +card2)) statement to loop until the player either sticks or busts.
from what I can see, it should work... but I'm missing a detail, and I can't figure out what.
import java.util.Random;
import java.util.Scanner;
class Blackjack
{
public static void main(String[] args)
{
Random r = new Random();
String name;
Scanner scannerIn = new Scanner(System.in);
boolean yourTurn = true;
boolean dealersTurn =true;
int card1 = 1 + r.nextInt(11);
int card2 = 1 + r.nextInt(11);
int dcard1 = 1 + r.nextInt(11);
int dcard2 = 1 + r.nextInt(11);
int pscore = card1 +card2;
int dscore = dcard1 +dcard2;
System.out.println("Welcome to Blackjack ! " );
System.out.println("\nScore as close to 21 without going over to win ");
System.out.println("\nWhat is your name?");
name = scannerIn.nextLine();
System.out.println("\nHello " + name);
System.out.println("\nLet's play some BlackJack!");
System.out.println("\nThe dealer shows:\t" +dcard1 );
System.out.println("\n\nYour first card is:\t " +card1 );
System.out.println("\nYour second card is:\t" +card2 );
System.out.println("\nGiving you a grand total of: " +pscore );
while (yourTurn)
{
if ((pscore <= +card1 +card2))
System.out.println("\nWould you like to (H)it or (S)tick?");
String a = scannerIn.nextLine();
if(a.toLowerCase().equals("h"))
{
int newCard = 1 + r.nextInt(11);
System.out.println("\nYour next card is " +newCard );
pscore = pscore +newCard;
System.out.println("\nGiving you a new total of "+pscore);
if ((pscore >=22))
{
System.out.println("\nYou Busted! \nSorry! you lose");
yourTurn = false;break;
}
}
else if(a.toLowerCase().equals("s"))
{
yourTurn = false;
System.out.println("\nYou stick at " +pscore );
System.out.println("\nNow it's the dealers turn\n Dealer must draw until 17");
}
else
{
System.out.println("\nPlease press H or S");
}
while (dealersTurn)
{
dealersTurn = true;
{ if ((dscore <= dcard1+dcard2))
System.out.println("\nThe dealers cards were:\n " +dcard1);
System.out.println("\nand\n" +dcard2);
System.out.println("\nGiving the Dealer a grand total of: " +dscore );
}
{
int newCard1 = 1 + r.nextInt(11);
if ((dscore<=17))
System.out.println("\nThe dealer draws a: " +newCard1 );
dscore = dscore +newCard1;
System.out.println("\nGiving the dealer a grand total of: "+dscore);
}
if ((dscore >=22))
{
System.out.println("\nDealer Bust!");
System.out.println("\nThe House loses");
System.out.println("\nYou Win");
dealersTurn = false;break;
}
else if ((dscore >=pscore))
{
System.out.println("\nDealer has " +dscore);
System.out.println("\nThe dealer beat you!");
System.out.println("\nThe House Wins!");
dealersTurn = false;break;
}
}
}
scannerIn.close();
}
}
Also, I have a bunch of people to thank, helping me get this far. If there is a +1 button for people I can't find it.
Thanks for the help
Vincent.
Your while(yourTurn) loop does not close its bracket until after the while(dealerTurn) loop. This is causing the dealers turn to be a part of the yourTurn loop. Add a closing bracket above the dealersTurn while loop as follows:
}
while (dealersTurn)
{
Then remove the old closing bracket from the bottom above "scannerIn.close()"
But also, what is the purpose of your logic
if ((pscore <= +card1 +card2))
Your score is = to card1 + card2 and then if you draw another card your score will be greater than those 2 cards since you have 3 cards now. That is why it is also not entering your if statement.

The Pig Dice Game Human vs Computer Java Program

I have been working on this program for about a week now and I think I have it down pack. The issue I am having when I ask the user at the beginning of the game (human vs computer) every time I run the program it asks me what my name is again. Here is what I have thus far:
import java.util.Scanner;
public class Assignment
{
Scanner usersName;
Boolean humanTurn = true;
Boolean computerTurn = true;
int dice;
int humanTurnPoints, computerTurnPoints;
int humanTotalPoints = 0;
int computerTotalPoints = 0;
private Scanner keyboard;
private Scanner key;
//System.out.print("Please enter your name: ");
//usersName = new Scanner(System.in);
//setStart(usersName.nextLine());
public void roll()
{
dice = (int)(Math.random()*6) + 1;
}
public int humanTurnScore()
{
{
humanTurnPoints = dice + humanTurnPoints;
System.out.println("You threw: " + dice);
System.out.println("You have scored: " + humanTurnPoints + " in your turn.");
} return humanTurnPoints;
}
public void humanTurnZero()
{
humanTurnPoints = 0;
}
public int computerTurnScore()
{
{
computerTurnPoints = dice + computerTurnPoints;
System.out.println("Computer has scored: " + computerTurnPoints + " in its turn.");
} return computerTurnPoints;
}
public void computerTurnZero()
{
computerTurnPoints = 0;
}
public Assignment()
{
humanGame();
if(!humanTurn)
{
computerTurn();
}
}
public int humanGame()
{
System.out.println("To start the game please press 'r'.");
key = new Scanner(System.in);
String start = key.nextLine();
if(!start.equalsIgnoreCase("R"))
{
System.out.println("Make sure you are pressing 'r'.");
humanGame();
}
if(start.equalsIgnoreCase("R"))
{
System.out.println("You pressed 'r'.");
System.out.println("Lets start.");
do{
roll();
if(dice == 1)
{
System.out.println("You got 1 and you lost your turn.");
System.out.println("Computer's GRAND TOTAL score is: " + computerTotalPoints);
humanTurnZero();
computerTurn();
}
else if(dice != 1)
{
humanTotalPoints += dice;
if(humanTotalPoints >= 100)
{
System.out.println("You threw: " + dice);
System.out.println("Your GRAND TOTAL score is: " + humanTotalPoints);
System.out.println("Congratulations, you win!");
System.exit(0);
}
humanTurnScore();
System.out.println("Your GRAND TOTAL score is: " + humanTotalPoints);
System.out.println("Computer's GRAND TOTAL score is: " + computerTotalPoints);
System.out.println("You can hold or roll again.");
System.out.println("To roll again press 'r' or 'h' to hold.");
keyboard = new Scanner(System.in);
String choice = keyboard.nextLine();
if(choice.equalsIgnoreCase("R"))
{
System.out.println("You pressed 'r'.");
System.out.println("Lets roll again.");
roll();
if(!choice.equalsIgnoreCase("R"))
{
System.out.println("You didn't press 'r'. To make sure the program is running correctly please press 'r' to roll or 'h' to hold.");
humanGame();
}
}
if(choice.equalsIgnoreCase("h"))
{
System.out.println("You pressed 'h' and loose your turn.");
System.out.println("Your Grand total is: " + humanTotalPoints);
humanTurnZero();
computerTurn();
}
}
}while(humanTurn);
}return dice;
}
public int computerTurn()
{
System.out.println("Now it's computer turn.");
do {
roll();
if(dice != 1)
{
computerTotalPoints += dice;
if(computerTotalPoints >=100)
{
System.out.println("Computer threw: " + dice);
System.out.println("Computer's GRAND TOTAL score is: " + computerTotalPoints);
System.out.println("Game Over! the computer wins");
System.exit(0);
}
System.out.println("Computer threw: " + dice);
System.out.println("Computer's GRAND TOTAL score is: " + computerTotalPoints);
System.out.println("Your Grand total is: " + humanTotalPoints);
computerTurnScore();
roll();
}
if(dice == 1)
{
System.out.println("Computer thrown 1 therefore it's your turn now.");
computerTurnZero();
humanGame();
}
if(computerTurnPoints >= 20)
{
System.out.println("Computer scored already " + computerTurnPoints + " you'd better start to focus.");
System.out.println("Please play again");
humanGame();
}
}while (computerTurn);
return dice;
}
public static void main(String[] args)
{
new Assignment();
}
}
I commented out (up close to the top of the program) where I am asking the user at the beginning of the program what their name is. I actually need in all the System.out.println where it says 'You' I need it to say the usersName.
Would someone please help me with this program. I know someone is kind enough to help me out here.
Thank you in advance.
Of course it will ask you that every time!
You need to save this in a file, and then read from it!
//Write
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println(usersName.nextLine());
writer.close();
//Read
BufferedReader br = new BufferedReader(new FileReader("the-file-name.txt"));
try {
while (line != null) {
usersName = line;
line = br.readLine();
}
} finally {
br.close();
}
Add your logic for determining if there is sth in that file yourself please.
Okay, I think you might be getting confused about the lifetimes of variables. In java, variables like String username; exist only in their own scope.
If you define a variable inside a method, it will be forgotten about when the program exists the method.
If you define it as a field inside a class (what you were doing), it will only exist as long as the instance of the class exists. As soon as the program forgets about the instance of the class, it also forgets about anything attached to that instance, including its variables.
Once the program shuts down, the computer naturally forgets about all objects that the program held, and so the username ceases to exist.
If you want the program to remember some value across shutdowns, you have to store that value in a file or a database or whatever. I recommend using a file, to make a database for this would be overkill squared. I will refer you to Roberto's answer from an hour ago for more info on how to achieve this exacly.

Categories