How do I make amount() in class Casino.java store the total value and allow it to be returned to the class Roulette.java.
When I use:
int amount = Casino.amount();
It gives me several hundred lines of errors.
What I want done is to run the game number() and store the value into Casino.amount()
Please note in class Roulette.java there is a function called amountUpdate() which should update Casino.amount().
This is class Casino.java
package Casino;
import java.util.*;
public class Casino {
static String player = "";
static int playAmount = 0;
public static void main(String[] args) {
System.out.println("Welcome to Michael & Erics Casino!");
player();
ask();
start();
}
public static String player() {
if (player.equals("")) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your name : ");
player = sc.nextLine();
}
return player;
}
public static void ask() {
Scanner sc = new Scanner(System.in);
System.out.println("How much would you like to play with? ");
playAmount = sc.nextInt();
if (playAmount < 1) {
System.out.println("Please enter a value that is more than $1");
playAmount = 0;
}
System.out.println("You are playing with: $" + playAmount + "\n");
}
public static int amount() {
int amount = playAmount;
if (Roulette.amountUpdate() >= 1) {
amount += Roulette.amountUpdate();
}
return amount;
/*if (Blackjack.amountUpdate() >= 1)
amount += Blackjack.amountUpdate();
return amount;*/
}
public static void start() {
System.out.println("Which table would you like to play at?");
System.out.println("1: Blackjack");
System.out.println("2: Roulette");
System.out.println("3: Check Balance");
System.out.println("4: Exit");
Scanner sc = new Scanner(System.in);
int table = sc.nextInt();
switch (table) {
case 1:
//blackjack.main(new String[]{});
break;
case 2:
Roulette.main(new String[]{});
break;
case 3:
System.out.println("You have : $" + playAmount);
start();
break;
case 4:
System.exit(0);
break;
}
}
}
This is class Roulette.java
package Casino;
import java.util.*;
import java.lang.*;
public class Roulette {
public static void main(String[] args) {
System.out.println("Welcome to the roulette table " + Casino.player());
placeBet();
amountUpdate();
//number();
}
public static int amountUpdate() {
int amount = 0;
if (number() > 0) {
amount += number();
}
if (br() > 0) {
amount += br();
}
if (oe() > 0) {
amount += oe();
}
if (third() > 0) {
amount += third();
}
return amount;
}
public static void placeBet() {
Scanner sc_Choice = new Scanner(System.in);
System.out.println("What would you like to bet on?");
System.out.println("1: Numbers");
System.out.println("2: Black or Red");
System.out.println("3: Odd or Even");
System.out.println("4: One Third");
System.out.println("5: Count Chips");
System.out.println("6: Restart");
int choice = sc_Choice.nextInt();
if (choice > 0 && choice < 7) {
switch (choice) {
case 1:
number();
break;
case 2:
br();
break;
case 3:
oe();
break;
case 4:
third();
break;
case 5:
System.out.println(Casino.amount());
break;
case 6:
Casino.main(new String[]{});
break;
}
} else {
System.out.println("You must choose between 1 and 6");
}
}
public static int number() {
Boolean betting = true;
//int amount = Casino.amount();
int amount = 5000;
int number;
int winnings;
String reply;
int betX;
int betAgain = 1;
Scanner sc_Number = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<Integer> bet = new ArrayList<Integer>();
while (betAgain == 1) {
System.out.println("What number would you like to place a bet on?");
int listCheck = sc_Number.nextInt();
if (listCheck >= 0 && listCheck <= 36) {
list.add(listCheck);
} else {
System.out.println("You must choose a number between 0 and 36");
}
System.out.println("How much do you want to bet?");
betX = sc_Number.nextInt();
if (betX > amount) {
System.out.println("You have insufficient funds to make that bet");
number();
} else if (betX < 1) {
System.out.println("You must bet more than 1$");
} else {
bet.add(betX);
amount = amount - betX;
}
System.out.println("Do you want to bet on more numbers?");
reply = sc_Number.next();
if (reply.matches("no|No|false|nope")) {
betAgain = betAgain - 1;
//No - Don't bet again
} else {
betAgain = 1;
//Yes - Bet again
}
int result = wheel();
System.out.println("Spinning! .... The number is: " + result);
for (int i = 0; i < bet.size(); i++) {
if (list.get(i) == result) {
winnings = bet.get(i) * 35;
System.out.println("Congratulations!! You won: $" + winnings);
amount = amount + winnings;
System.out.println("Current Balance: " + amount);
betAgain = betAgain - 1;
} else {
System.out.println("Sorry, better luck next time!");
System.out.println("Current Balance: " + amount);
betAgain = betAgain - 1;
}
}
betAgain = betAgain - 1;
}
return amount;
}
public static int wheel() {
Random rnd = new Random();
int number = rnd.nextInt(37);
return number;
}
//NOT WORKING - AFTER MAKING A BET IT RUNS Number()
public static int br() {
Scanner sc_br = new Scanner(System.in);
int amount = Casino.amount();
int winnings;
System.out.println("Would you like to bet on Black or Red?");
String replyBR = sc_br.nextLine();
boolean black;
//****************
if (replyBR.matches("black|Black")) {
black = true;
} else {
black = false;
}
System.out.println("How much would you like to bet?");
int betBR = sc_br.nextInt();
if (betBR > amount) {
System.out.println("You have insufficient funds to make that bet");
br();
} else if (betBR < 1) {
System.out.println("You must bet more than 1$");
br();
} else {
amount = amount - betBR;
}
//*****************
boolean resultColour = colour();
if (resultColour == black) {
winnings = betBR * 2;
//PRINT OUT WHAT COLOUR!!!
System.out.println("Congratulations!! You won: $" + winnings);
amount = amount + winnings;
System.out.println("Current Balance: " + amount);
} else {
System.out.println("Sorry, better luck next time!");
}
System.out.println("Current Balance: " + amount);
return amount;
}
public static boolean colour() {
Random rnd = new Random();
boolean colour = rnd.nextBoolean();
return colour;
}
//NOT WORKING - AFTER MAKING A BET IT RUNS Number()
public static int oe() {
Scanner sc_oe = new Scanner(System.in);
int amount = Casino.amount();
int winnings;
System.out.println("Would you like to bet on Odd or Even?");
String replyOE = sc_oe.next();
System.out.println("How much would you like to bet?");
int betOE = sc_oe.nextInt();
if (betOE > amount) {
System.out.println("You have insufficient funds to make that bet");
oe();
}
amount = amount - betOE;
boolean resultOE = oddOrEven();
//PRINT OUT IF IT WAS ODD OR EVEN
if (resultOE == true) {
winnings = betOE * 2;
System.out.println("Congratulations!! You won: $" + winnings);
amount = amount + winnings;
System.out.println("Current Balance: " + amount);
} else {
System.out.println("Sorry, better luck next time!");
System.out.println("Current Balance: " + amount);
}
return amount;
}
public static boolean oddOrEven() {
Random rnd = new Random();
boolean num = rnd.nextBoolean();
return num;
}
//NOT WORKING - AFTER MAKING A BET IT RUNS Number()
public static int third() {
Scanner sc_Third = new Scanner(System.in);
int amount = Casino.amount();
int winnings;
System.out.println("Would you like to bet on 1st, 2nd or 3rd third?");
String replyT = sc_Third.next();
System.out.println("How much would you like to bet?");
int betT = sc_Third.nextInt();
if (betT > amount) {
System.out.println("You have insufficient funds to make that bet");
third();
}
amount = amount - betT;
boolean resultT = thirdResult();
//PRINT OUT WHAT NUMBER IT WAS AND IF IT WAS IN WHICH THIRD
if (resultT == true) {
winnings = betT * 3;
System.out.println("Congratulations!! You won: $" + winnings);
amount = amount + winnings;
System.out.println("Current Balance: " + amount);
} else {
System.out.println("Sorry, better luck next time!");
System.out.println("Current Balance: " + amount);
}
return amount;
}
public static boolean thirdResult() {
Random rnd = new Random();
int num = rnd.nextInt(2);
if (num == 0) {
return true;
} else {
return false;
}
}
}
Looks like you're probably running into a StackOverflowException. When you call Casino.amount() inside of Roulette.number(), it then calls Roulette.amountUpdate(), which then calls Roulette.number(). Your methods are stuck in an infinite loop like this. You'll need to redesign your code such that these 3 functions are not all dependent on each other.
Your code is terse, so it's hard to help you fully solve the problem, but I believe you would benefit from splitting up your "amount" variable into separate entities. Keep things like bet amount, winnings, and such separate until you need to combine them.
Another issue you may run into is thatRoulette.amountUpdate() is called twice in Casino.amount(), but Roulette.amountUpdate() will not necessarily return the same thing both times. Consider storing the return value from the first call instead of calling it twice.
Related
So I'm in the midst of creating a gambling application and just as I'm about to close up for the night. I see there is a new error all the way at the bottom with my closing brackets.
I'm getting the following error Syntax on error "{", "}" expected.
I think there might be an issue with one of my methods, but all of the brackets seem to be placed correctly. I apologize that it's 200+ lines of code, but if someone could possibly point out where I went wrong to get this error, I'd really appreciate it. I've tried messing with my brackets, but that only seems to lead to further errors.
import java.util.Scanner;
import java.util.Random;
public class Project2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int min = 1;
int max = 10;
int colmax = 2;
double balance = 2500.0;
double bet1 = 0;
double bet2 = 0;
double profit1 = (bet1 * 2) - bet1;
double profit2 = (bet2 * 5) - bet2;
String kBet = null;
System.out.println(" -==-==-==-==-==-==-==-==-==-==-" );
System.out.println("-==-==-=={ Welcome to the Marist Casino! }==-==-==-");
System.out.println(" -==-==-==-==-==-==-==-==-==-==-" );
System.out.println("(1) Red Fox Roullete");
System.out.println("(2) Crash");
System.out.println("(3) Blackjack");
System.out.print("Enter the number for the game you'd like to play!: ");
int game = input.nextInt();
if(game == 1) {
do {
System.out.println("---------------------------------------------");
System.out.println("Welcome to Red Fox Roullete!");
System.out.print("Please choose Black or Red....and a number from 1-10: ");
String color = input.next();
int number = input.nextInt();
System.out.print("Your available balance is $"+balance+". How much would you like to bet on "+color+"?");
bet1 = input.nextInt();
balance -= bet1;
System.out.print("Your available balance is $"+balance+". How much would you like to bet on "+number+"?");
bet2 = input.nextInt();
balance -= bet2;
System.out.println("------------------------------BET INFO------------------------------------");
System.out.println("You just bet $"+bet1+" on "+color+" and $"+bet2+" on number "+number);
System.out.println("Spinning............");
System.out.println("------------------------------RESULTS-------------------------------------");
Random rouletteNum = new Random();
int rNum = min + rouletteNum.nextInt(max);
int rCol = min + rouletteNum.nextInt(colmax);
if (rCol == 1) {
System.out.println("The machine landed on Black "+rNum);
}
else if(rCol != 1) {
System.out.println("The machine landed on Red "+rNum);
}
if(rNum == number) {
System.out.println("Congrats, you guessed the right number! You've won $"+profit2);
balance += (bet2 * 5);
}
else if(rNum != number) {
System.out.println("Sorry!You didnt guess the right number! You've lost "+bet2);
}
if(rCol == 1 && color.equals("Black")) {
System.out.println("Congrats, you guessed the right color! You've won $"+profit1);
balance += bet1 * 2 - bet1;
}
else if(rCol == 2 && color.equals("Red")) {
System.out.println("Congrats, you guessed the right color! You've won $"+profit1);
balance += bet1 * 2 - bet1;
}
if(rCol == 2 && color.equals("Black")) {
System.out.println("Sorry, you didn't guess the right color. You've lost $"+bet1);
}
else if(rCol == 1 && color.equals("Red")) {
System.out.println("Sorry, you didn't guess the right color. You've lost $"+bet1);
}
System.out.println("After the bet, you're updated balance is $"+balance);
System.out.println("-----------------------------------------------------------------");
System.out.print("Yes or No? Would you like to place another bet in Roulette?");
kBet = input.next();
}
while(kBet.equals("Yes"));
if(kBet.equals("No")) {
System.out.println("(1) Red Fox Roullete");
System.out.println("(2) Blackjack");
System.out.println("(3) Crash");
System.out.print("Enter the number for the game you'd like to play!: ");
game = input.nextInt();
}
}
//CRASH
else if (game == 2) {
do {
int bet = 0;
double start = 1.00;
double crashValue = 1.00;
int stopGame = 1;
double cashout = 0;
System.out.println("-------------------CRASH GAME--------------------------");
System.out.println("Welcome to Crash!");
System.out.print("What number would you like to cashout at?(Ex. 1.15):");
cashout = input.nextDouble();
System.out.print("Your balance is $"+balance+". How much would you like to bet on this round?:");
bet = input.nextInt();
System.out.println("--------------------------------------------------------------------------");
System.out.println("Round is beginning.........");
for(int i =0; i < stopGame; i++) {
do {
double crash = Math.random() * 100;
if (crash < 95) {
start += .01;
System.out.printf("%.2f\n",start);
}
else if(crash > 95) {
i++;
crashValue = start;
System.out.println("----------------------------RESULTS--------------------------------");
System.out.print("CRASH! The game crashed at ");
System.out.printf("%.2f",start);
System.out.println("x");
}
}
while(i == 0);
}
if(cashout < crashValue) {
System.out.println("Congrats! You cashed out at "+cashout+" before the game crashed. You've won $"+bet*cashout);
balance += bet * cashout;
}
else {
System.out.println("Sorry! The game crashed before you could cash out. You've lost $"+bet);
balance -= bet;
}
System.out.println("After your bet, you're updated balance is $"+balance);
System.out.println("-------------------------------------------------------------------");
System.out.print("Yes or No? Would you like to play another round of Crash?: ");
kBet = input.next();
}
while(kBet.equals("Yes"));
if(kBet.equals("No")) {
System.out.println("(1) Red Fox Roullete");
System.out.println("(2) Blackjack");
System.out.println("(3) Crash");
System.out.print("Enter the number for the game you'd like to play!: ");
game = input.nextInt();
}
}
//BlackJack Game
else if(game == 3) {
Scanner input1 = new Scanner(System.in);
System.out.println("---------------------Black Jack--------------------------");
System.out.println("Welcome to BlackJack!");
System.out.println("Available balance is $"+balance);
System.out.print("How much would you like to bet on this hand?: ");
int bet = input.nextInt();
balance -= bet;
System.out.println("You just bet $"+bet+"......Dealing cards!");
System.out.println("----------------------------------------------------------");
String pCard1 = dealCard();
String pCard2 = dealCard();
int value1 = getCardValue(pCard1);
int value2 = getCardValue(pCard2);
System.out.println("Your hand is a "+pCard1+" and a "+pCard2);
System.out.print("Would you like to Hit or Stand?: ");
String HitOrStand = input.next();
}
}
public static String dealCard() {
int rCard = (int)Math.random() * 14;
switch(rCard) {
case 1 : return "2";
case 2 : return "3";
case 3 : return "4";
case 4 : return "5";
case 5 : return "6";
case 6 : return "7";
case 7 : return "8";
case 8 : return "9";
case 9 : return "10";
case 10 : return "Queen";
case 11 : return "Jack";
case 12 : return "King";
case 13 : return "Ace";
}
}
public static int getCardValue(String x) {
if(x.equals("2")) {
return 2;
}
if(x.equals("3")) {
return 3;
}
if(x.equals("4")) {
return 4;
}
if(x.equals("5")) {
return 5;
}
if(x.equals("6")) {
return 6;
}
if(x.equals("7")) {
return 7;
}
if(x.equals("8")) {
return 8;
}
if(x.equals("9")) {
return 9;
}
if(x.equals("10")) {
return 10;
}
if(x.equals("Queen")) {
return 10;
}
if(x.equals("Jack")) {
return 10;
}
if(x.equals("King")) {
return 10;
}
if(x.equals("Ace")) {
return 11;
}
}
}
}
}
Two more brackets and two missing return:
import java.util.Scanner;
import java.util.Random;
public class Project2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int min = 1;
int max = 10;
int colmax = 2;
double balance = 2500.0;
double bet1 = 0;
double bet2 = 0;
double profit1 = (bet1 * 2) - bet1;
double profit2 = (bet2 * 5) - bet2;
String kBet = null;
System.out.println(" -==-==-==-==-==-==-==-==-==-==-" );
System.out.println("-==-==-=={ Welcome to the Marist Casino! }==-==-==-");
System.out.println(" -==-==-==-==-==-==-==-==-==-==-" );
System.out.println("(1) Red Fox Roullete");
System.out.println("(2) Crash");
System.out.println("(3) Blackjack");
System.out.print("Enter the number for the game you'd like to play!: ");
int game = input.nextInt();
if(game == 1) {
do {
System.out.println("---------------------------------------------");
System.out.println("Welcome to Red Fox Roullete!");
System.out.print("Please choose Black or Red....and a number from 1-10: ");
String color = input.next();
int number = input.nextInt();
System.out.print("Your available balance is $"+balance+". How much would you like to bet on "+color+"?");
bet1 = input.nextInt();
balance -= bet1;
System.out.print("Your available balance is $"+balance+". How much would you like to bet on "+number+"?");
bet2 = input.nextInt();
balance -= bet2;
System.out.println("------------------------------BET INFO------------------------------------");
System.out.println("You just bet $"+bet1+" on "+color+" and $"+bet2+" on number "+number);
System.out.println("Spinning............");
System.out.println("------------------------------RESULTS-------------------------------------");
Random rouletteNum = new Random();
int rNum = min + rouletteNum.nextInt(max);
int rCol = min + rouletteNum.nextInt(colmax);
if (rCol == 1) {
System.out.println("The machine landed on Black "+rNum);
}
else if(rCol != 1) {
System.out.println("The machine landed on Red "+rNum);
}
if(rNum == number) {
System.out.println("Congrats, you guessed the right number! You've won $"+profit2);
balance += (bet2 * 5);
}
else if(rNum != number) {
System.out.println("Sorry!You didnt guess the right number! You've lost "+bet2);
}
if(rCol == 1 && color.equals("Black")) {
System.out.println("Congrats, you guessed the right color! You've won $"+profit1);
balance += bet1 * 2 - bet1;
}
else if(rCol == 2 && color.equals("Red")) {
System.out.println("Congrats, you guessed the right color! You've won $"+profit1);
balance += bet1 * 2 - bet1;
}
if(rCol == 2 && color.equals("Black")) {
System.out.println("Sorry, you didn't guess the right color. You've lost $"+bet1);
}
else if(rCol == 1 && color.equals("Red")) {
System.out.println("Sorry, you didn't guess the right color. You've lost $"+bet1);
}
System.out.println("After the bet, you're updated balance is $"+balance);
System.out.println("-----------------------------------------------------------------");
System.out.print("Yes or No? Would you like to place another bet in Roulette?");
kBet = input.next();
}
while(kBet.equals("Yes"));
if(kBet.equals("No")) {
System.out.println("(1) Red Fox Roullete");
System.out.println("(2) Blackjack");
System.out.println("(3) Crash");
System.out.print("Enter the number for the game you'd like to play!: ");
game = input.nextInt();
}
}
//CRASH
else if (game == 2) {
do {
int bet = 0;
double start = 1.00;
double crashValue = 1.00;
int stopGame = 1;
double cashout = 0;
System.out.println("-------------------CRASH GAME--------------------------");
System.out.println("Welcome to Crash!");
System.out.print("What number would you like to cashout at?(Ex. 1.15):");
cashout = input.nextDouble();
System.out.print("Your balance is $"+balance+". How much would you like to bet on this round?:");
bet = input.nextInt();
System.out.println("--------------------------------------------------------------------------");
System.out.println("Round is beginning.........");
for(int i =0; i < stopGame; i++) {
do {
double crash = Math.random() * 100;
if (crash < 95) {
start += .01;
System.out.printf("%.2f\n",start);
}
else if(crash > 95) {
i++;
crashValue = start;
System.out.println("----------------------------RESULTS--------------------------------");
System.out.print("CRASH! The game crashed at ");
System.out.printf("%.2f",start);
System.out.println("x");
}
}
while(i == 0);
}
if(cashout < crashValue) {
System.out.println("Congrats! You cashed out at "+cashout+" before the game crashed. You've won $"+bet*cashout);
balance += bet * cashout;
}
else {
System.out.println("Sorry! The game crashed before you could cash out. You've lost $"+bet);
balance -= bet;
}
System.out.println("After your bet, you're updated balance is $"+balance);
System.out.println("-------------------------------------------------------------------");
System.out.print("Yes or No? Would you like to play another round of Crash?: ");
kBet = input.next();
}
while(kBet.equals("Yes"));
if(kBet.equals("No")) {
System.out.println("(1) Red Fox Roullete");
System.out.println("(2) Blackjack");
System.out.println("(3) Crash");
System.out.print("Enter the number for the game you'd like to play!: ");
game = input.nextInt();
}
}
//BlackJack Game
else if(game == 3) {
Scanner input1 = new Scanner(System.in);
System.out.println("---------------------Black Jack--------------------------");
System.out.println("Welcome to BlackJack!");
System.out.println("Available balance is $"+balance);
System.out.print("How much would you like to bet on this hand?: ");
int bet = input.nextInt();
balance -= bet;
System.out.println("You just bet $"+bet+"......Dealing cards!");
System.out.println("----------------------------------------------------------");
String pCard1 = dealCard();
String pCard2 = dealCard();
int value1 = getCardValue(pCard1);
int value2 = getCardValue(pCard2);
System.out.println("Your hand is a "+pCard1+" and a "+pCard2);
System.out.print("Would you like to Hit or Stand?: ");
String HitOrStand = input.next();
}
}
public static String dealCard() {
int rCard = (int)Math.random() * 14;
switch(rCard) {
case 1 : return "2";
case 2 : return "3";
case 3 : return "4";
case 4 : return "5";
case 5 : return "6";
case 6 : return "7";
case 7 : return "8";
case 8 : return "9";
case 9 : return "10";
case 10 : return "Queen";
case 11 : return "Jack";
case 12 : return "King";
case 13 : return "Ace";
}
return "Unknown";
}
public static int getCardValue(String x) {
if(x.equals("2")) {
return 2;
}
if(x.equals("3")) {
return 3;
}
if(x.equals("4")) {
return 4;
}
if(x.equals("5")) {
return 5;
}
if(x.equals("6")) {
return 6;
}
if(x.equals("7")) {
return 7;
}
if(x.equals("8")) {
return 8;
}
if(x.equals("9")) {
return 9;
}
if(x.equals("10")) {
return 10;
}
if(x.equals("Queen")) {
return 10;
}
if(x.equals("Jack")) {
return 10;
}
if(x.equals("King")) {
return 10;
}
if(x.equals("Ace")) {
return 11;
}
return -1;
}
}
i am having trouble passing the value of "guess" into my main method. The
method that is trying to return guess just shows up as zero in the main.I have tried various things such as void methods and different returns but the guess value does not get updated in the while loop of the main even though, from what i am seeing, it should be getting updated from the method and passing it down to the guesses right below it.
import java.util.*;
public class assignment052 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int userGuess = 0;
int compNum = 0;
int guess = 0;
int totalGuesses = 0; //
int best = 9999; //
introduction();
int games = 0;
String playAgain = "y";
while(playAgain.equalsIgnoreCase("y")) {
System.out.println();
System.out.println("I'm thinking of a number between 1 and 100...");
games++;
guessNumber(console, userGuess, compNum, guess);
System.out.println(guess);
totalGuesses += guess;
System.out.println("Do you want to play again?");
Scanner newGame = new Scanner(System.in);
playAgain = newGame.next();
if (best > guess) { //
best = guess; //
}
}
result(games, totalGuesses, best);
}
// Method that introduces the game
public static void introduction() {
System.out.println("This program allows you to play a guessing game.");
System.out.println("I will think of a number between 1 and");
System.out.println("100 and will allow you to guess until");
System.out.println("you get it. For each guess, I will tell you");
System.out.println("whether the right answer is higher or lower");
System.out.println("than your guess.");
}
// method to play 1 game
public static double guessNumber(Scanner console, int userGuess, int compNum, int guess) {
Random rand = new Random();
userGuess = console.nextInt();
guess = 1;
compNum = rand.nextInt(100)+1;
while(compNum != userGuess) {
if(compNum > userGuess) {
System.out.println("It's higher.");
} else {
System.out.println("It's lower.");
}
guess++;
userGuess = console.nextInt();
}
System.out.println("you got it right in " + guess + " guesses");
return guess;
}
// method for overall result
public static void result(int games, int totalGuesses, int best) {
System.out.println("Overall results:");
System.out.println();
System.out.println("Total games played : " + games);
System.out.println("Total guesses : " + totalGuesses);
System.out.println("Guesses per game : " + totalGuesses / games);
}
}
I have a game that's running perfectly. I want to put a line of code that asks the player if they want to play again at the end of the game. I would also like to keep a score system for every player and computer win.
I'm having trouble with the input = Integer.parseInt(sc.nextInt()); line
import java.util.Scanner;
public class Sticks {
public static boolean whoStart(String choice) {
int ran = (int) (Math.random() * 2 + 1);
String ht = "";
switch (ran) {
case 1:
ht = "head";
break;
case 2:
ht = "tails";
}
if (ht.equals(choice.toLowerCase())) {
System.out.println("you start first");
return true;
} else {
System.out.println("computer starts first");
return false;
}
}
public static int playerTurn(int numberOfSticks) {
System.out.println(" \nthere are " + numberOfSticks + " sticks ");
System.out.println("\nhow many sticks do you wanna take? 1 or 2?");
Scanner in = new Scanner(System.in);
int sticksToTake = in.nextInt();
while ((sticksToTake != 1) && (sticksToTake != 2)) {
System.out.println("\nyou can only take 1 or 2 sticks");
System.out.println("\nhow many sticks do you wanna take?");
sticksToTake = in.nextInt();
}
numberOfSticks -= sticksToTake;
return numberOfSticks;
}
public static int computerTurn(int numberOfSticks) {
int sticksToTake;
System.out.println("\nthere are " + numberOfSticks + " sticks ");
if ((numberOfSticks - 2) % 3 == 0 || (numberOfSticks - 2 == 0)) {
sticksToTake = 1;
numberOfSticks -= sticksToTake;
} else {
sticksToTake = 2;
numberOfSticks -= sticksToTake;
}
System.out.println("\ncomputer took " + sticksToTake + " stick ");
return numberOfSticks;
}
public static boolean checkWinner(int turn, int numberOfSticks) {
int score = 0;
int input;
int B = 1;
int Y=5, N=10;
if ((turn == 1) && (numberOfSticks <= 0)) {
System.out.println("player lost");
return true;
}
if ((turn == 2) && (numberOfSticks <= 0)) {
System.out.println("player won");
score++;
return true;
}
System.out.println("Your score is "+ score);
System.out.println("Do you want to play again? Press (5) for Yes / (10) for No");
// ----- This line -----
input = Integer.parseInt(sc.nextInt());
if (input == Y) {
B = 1;
System.out.println("Rock, Paper, Scissors");
} else if (input == N) {
System.exit(0);
System.out.println("Have A Good Day!");
}
}
public static void main(String args[]) {
int turn;
int numberOfSticks = 21;
Scanner in = new Scanner(System.in);
System.out.println("choose head or tails to see who starts first");
String choice = in.next();
if (whoStart(choice) == true) {
do {
turn = 1;
numberOfSticks = playerTurn(numberOfSticks);
if (checkWinner(turn, numberOfSticks) == true) {
break;
};
turn = 2;
numberOfSticks = computerTurn(numberOfSticks);
checkWinner(turn, numberOfSticks);
} while (numberOfSticks > 0);
} else {
do {
turn = 2;
numberOfSticks = computerTurn(numberOfSticks);
if (checkWinner(turn, numberOfSticks) == true) {
break;
};
turn = 1;
numberOfSticks = playerTurn(numberOfSticks);
checkWinner(turn, numberOfSticks);
} while (numberOfSticks > 0);
}
}
}
The title of your question almost answered you what you need to add: a loop!
I suggest you to refactor your function main and extract all your game logic from it to be stored within a dedicated function for the sake of the readability. Let's call it startGame().
Your main is going to become shorter and can represent a good location to introduce this loop, such as:
public static void main(String[] a) {
boolean isPlaying = true;
Scanner in = new Scanner(System.in);
while(isPlaying) {
startGame();
// Your message to continue or stop the game
if(in.next().equalsIgnoreCase("No")) {
isPlaying = false;
}
}
}
I recommend you to use a boolean that is checked in your while loop rather than using a break statement, as it brings a better control flow in your application.
Just put everything in a while(true) loop and use a break; if they choose no. Something like:
static int playerPoints = 0;
public static void main(String args[]) {
int turn;
int numberOfSticks = 21;
Scanner in = new Scanner(System.in);
while(true){
...
System.out.println("You have " + playerPoints + " points!")
System.out.println("Do you want to play again?");
if (!in.nextLine().toLowerCase().equals("yes")){
break;
}
}
}
Edit: ZenLulz's answer is better than this one, mainly because it encourages better programming practice. Mine works but isn't the best way to solve the issue.
This code models a simple ATM machine that can deposit, withdraw, and show the 10 latest transactions in an array of 10 index values.
My problem is that I can't get the balance right after 10 deposits, the balance only seems to sum the values in my array, not including the transactions made before those ten. What am I doing wrong?
import java.util.Scanner;
public class cashier2 {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int amount = 0;
int choice = 0;
int[] transactions = new int[10];
int sum = 0;
int balance = 0;
while(choice != 4)
{
choice = menu();
switch(choice)
{
case 1:
System.out.print("deposit");
sum = keyboard.nextInt();
if(sum == 0)
{
System.out.print("wrong amount");
System.out.println();
System.out.println();
}
else
{
amount = (int) + sum;
makeTransactions(amount, transactions);
}
break;
case 2:
System.out.print("withdrawal ");
sum = keyboard.nextInt();
if(sum == 0)
{
System.out.print("wrong amount");
System.out.println();
System.out.println();
}
else
{
amount = (int) - sum;
makeTransactions(amount, transactions);
}
break;
case 3:
showTransactions(transactions, balance);
break;
case 4:
System.out.println("Exit");
break;
}
}
}
public static int menu()
{
Scanner keyboard = new Scanner(System.in);
int choice = 0;
System.out.println("Simple atm");
System.out.println();
System.out.println("1. deposit");
System.out.println("2. withdrawal");
System.out.println("3. balance");
System.out.println("4. exit");
System.out.println();
System.out.print("your choice: ");
choice = keyboard.nextInt();
return choice;
}
public static void showTransactions(int[] transactions, int balance)
{
System.out.println();
System.out.println("Tidigare transaktioner: ");
System.out.println();
for(int i = 0; i < transactions.length; i++)
{
if(transactions[i] == 0)
{
System.out.print("");
}
else
{
System.out.print(transactions[i] + "\n");
balance = balance + transactions[i];
}
}
System.out.println();
System.out.println("Saldo: " + balance + " kr" + "\n");
System.out.println();
}
public static void makeTransactions(int amount, int[] transactions)
{
int position = findNr(transactions);
if (position == -1)
{
moveTrans(transactions);
position = findNr(transactions);
transactions[position] = amount;
}
else
{
transactions[position] = amount;
}
}
public static int findNr(int[] transactions)
{
int position = -1;
for(int i = 0; i < transactions.length; i++)
{
if (transactions[i] == 0)
{
position = i;
break;
}
}
return position;
}
//}
public static void moveTrans(int [] transactions)
{
for(int i = 0; i < transactions.length-1; i++)
{
transactions[i] = transactions[i + 1];
}
transactions[transactions.length-1] = 0;
}
}
I am writing a program in Java that is a classic BlackJack Game.
The rules are the same,and we make choices as players and the dealer(CPU) plays under some rules.
My code, that is beneath, makes 2 seperate stacks of Deck(s),one for Player and one for Dealer and each one draws from a different Deck but i want to make them both(Player and Dealer) draw from the same Deck(s).
Any suggestions/corrections on my Code ?
import java.util.Random;
import java.util.Scanner;
public class River
{
private int CardNumber;
private int BeginCards;
private int Decks;
private int[] PartialSumArray = {4,8,12,16,20,24,28,32,36,52};
private int[] BeginPartialSumArray = {4,8,12,16,20,24,28,32,36,52};
private int PickedCard;
private Random randomGenerator = new Random();
//Constructor without definition
public River()
{
CardNumber = 52;
BeginCards = 52;
}
//Constructor with definition
public River(int Decks)
{
CardNumber = Decks * 52;
BeginCards = CardNumber;
this.Decks = Decks;
//Initialize partial sum array for many decks of cards
for (int i=0; i<10; i++)
{
PartialSumArray[i] = PartialSumArray[i] * Decks;
BeginPartialSumArray[i] = PartialSumArray[i] * Decks;
}
System.out.println();
}
//Create random numbers
private int computeRandomSteps(int CardNumber)
{
//System.out.print("stin random , cardnumber is" + CardNumber);
int randomSteps = randomGenerator.nextInt(CardNumber-1);
return randomSteps;
}
public int nextCard()
{
int steps = computeRandomSteps(CardNumber);
int position=0;
for (int i=0; i<CardNumber; i++)
{
if (steps<= PartialSumArray[i])
{
position = i+1;
break;
}
}
CardNumber--;
return position;
}
public int start()
{
int ShuffleLimit;
PickedCard = nextCard();
System.out.println("Picked card is :" + PickedCard);
int HelpVariable = PickedCard-1;
for (int i=0; i<10; i++)
{
if (i >= HelpVariable)
{
PartialSumArray[HelpVariable] = PartialSumArray[i]-1;
HelpVariable++;
}
}
ShuffleLimit = BeginCards/4;
if (CardNumber<ShuffleLimit)
{
for (int i=0; i<9; i++)
{
BeginPartialSumArray[i] = BeginPartialSumArray[i] * Decks;
}
}
return PickedCard;
}
public int ReturnCardNumber()
{
System.out.println("return cardnumber is " + CardNumber);
return CardNumber;
}
}
class Hand
{
private int points;
private int SumPoints=0;
private boolean Ace = true;
Scanner input = new Scanner(System.in);
//Scanner input3 = new Scanner(System.in);
//int Decks = input3.nextInt();
River myRiver = new River();
//River myRiver = new River(Decks);
public int getPoints()
{
points = myRiver.start();
if (points == 1 && Ace)
{
System.out.println("It is an Ace. Do you want to count 1 or 11?");
points = input.nextInt();
Ace = false;
}
SumPoints += points;
System.out.println("Points are : " + SumPoints);
return SumPoints;
}
public int getPointsDealer()
{
points = myRiver.start();
if (points == 1 && Ace)
{
if (SumPoints + 11 > 21)
{
points = 1;
}
else
{
points = 11;
}
Ace = false;
}
SumPoints += points;
System.out.println("Points are : " + SumPoints);
return SumPoints;
}
}
class Player
{
private int points;
private double account=0;
private double bet;
private boolean WinOrLose;
Scanner input1 = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
public double placeBet()
{
System.out.println("How much do you want to bet?");
bet = input1.nextDouble();
return bet;
}
public double profit(boolean WinOrLose)
{
if (WinOrLose)
{
account += bet;
return account;
}
else
{
account -= bet;
return account;
}
}
public int play(River other)
{
Hand myHand = new Hand();
bet = placeBet();
points = myHand.getPoints();
boolean end = true;
String Choice;
while (end)
{
System.out.println("Make a choice");
Choice = input2.nextLine();
switch(Choice)
{
case "DoubleBet":
bet = bet *2;
points = myHand.getPoints();
if (points > 21)
{
System.out.print("Burned!");
WinOrLose = false;
account = profit(WinOrLose);
end = false;
break;
}
else if (points == 21)
{
System.out.print("You won!");
WinOrLose = true;
account = profit(WinOrLose);
end = false;
break;
}
else
{
System.out.println("Your points are :" + points);
end = false;
break;
}
case "stop":
System.out.println("Your points are :" + points);
end = false;
break;
case "Hit":
points = myHand.getPoints();
if (points > 21)
{
System.out.print("Burned!");
WinOrLose = false;
account = profit(WinOrLose);
end = false;
break;
}
else if (points == 21)
{
System.out.print("You won!");
WinOrLose = true;
account = profit(WinOrLose);
end = false;
break;
}
break;
default:
System.out.println("That is not a choice.");
end = false;
break;
}
}
return points;
}
}
class BlackJack
{
public static void main(String args[])
{
int SumPointsPlayer;
int SumPointsDealer;
boolean WinOrLose = true;
double account;
int Decks;
int BeginCards;
int ThisMomentCards;
Scanner input1 = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
System.out.println("How many decks do you want to begin with?");
Decks = input1.nextInt();
River myRiver = new River(Decks);
Player myPlayer = new Player();
//Calculate the cards we have when the game starts
BeginCards = 52 * Decks;
System.out.println("Do you want to start the game? Yes or No.");
String Repeat;
Repeat = input2.nextLine();
while (Repeat.equals("Yes"))
{
ThisMomentCards = myRiver.ReturnCardNumber();
System.out.println("Cards are : " + ThisMomentCards);
//Player's points for 1 round
SumPointsPlayer = myPlayer.play(myRiver);
//If player catches 21 he wins instantly
if(SumPointsPlayer == 21)
{
account = myPlayer.profit(WinOrLose);
System.out.println("Your account has :" + account + "dollars!");
}
//If player catches >21 he loses instantly
else if(SumPointsPlayer > 21)
{
WinOrLose = false;
account = myPlayer.profit(WinOrLose);
System.out.println("Your account has :" + account + "dollars!");
}
//Compare the hand of player and dealer and the bigger wins
else
{
//Dealer's points for 1 round
SumPointsDealer = playDealer(myRiver);
//If dealer catches >21 he loses instantly
if(SumPointsDealer>21)
{
System.out.println("Player wins!");
account = myPlayer.profit(WinOrLose);
System.out.println("Your account has :" + account + "dollars!");
}
//Hand of player bigger than the hand of the dealer , player wins
else if (SumPointsPlayer>SumPointsDealer)
{
WinOrLose = true;
account = myPlayer.profit(WinOrLose);
System.out.println("Player wins. Your account has :" + account + "dollars!");
}
//Hand of player smaller than the hand of the dealer , dealer wins
else if (SumPointsPlayer<SumPointsDealer)
{
WinOrLose = false;
account = myPlayer.profit(WinOrLose);
System.out.println("Player lost. Your account has :" + account + "dollars!");
}
//Hand of player is equal with the hand of the dealer , it is tie
else
{
System.out.println("Player and Dealer are tie!!");
}
}
System.out.println("Do you want to continue the game? Yes or No.");
Repeat = input2.nextLine();
}
}
public static int playDealer(River other)
{
boolean bountry = true;
System.out.println("Dealer plays :");
Hand myHand = new Hand();
int SumPointsDealer = myHand.getPointsDealer();
while (bountry)
{
if (SumPointsDealer<17)
{
SumPointsDealer = myHand.getPointsDealer();
}
else if (SumPointsDealer>21)
{
System.out.println("Dealer burned!");
bountry = false;
}
else
{
bountry = false;
}
}
return SumPointsDealer;
}
}
Some Clarifications:
1) The way we draw randomly a card is based on a strange way but this is not the problem its ok the way the program Does draw randomly cards from the Decks
2) Another problem that i noticed is that in class Hand the code that i have in // is not working as it doesnt allow me to have a System.out.println()
Scanner input = new Scanner(System.in);
//Scanner input3 = new Scanner(System.in);
//int Decks = input3.nextInt();
River myRiver = new River();
//River myRiver = new River(Decks);
I wanted to do this so that i will say with how many Decks the user wants to play
You can do better and easier of code is oriented into objects.
i.e. Collections.shuffle(Deck) replaces that whole random conundrum
where Deck is your created Object made of such attributes as LinkedList and a counter[deck value]
hope that helps.
remove object Card from linked list of main deck and move it into the deck of a player. and yes, you can create as many decks as you want that way.
object Card has attributes Value and Suit.