My variable names are pretty stupid near the bottom but that's not the point. Line 110 says that I'm making an else statement without the if and I'm nearly certain the if is there. Please help in any way you can.
Thank you
import java.util.*;
public class hw7
{
public static void main(String[] args)
{
int turnScores = 0;
int totalScores = 0;
int turnScores2 = 0;
int totalScores2 = 0;
int dice;
int dice2;
String input = "r";
char repeat;
boolean peppers;
peppers = true;
Scanner keyboard = new Scanner(System.in);
Random randomNumbers = new Random();
System.out.println("Welcome to the game of Pig!\n");
while(totalScores < 20 || totalScores2 < 20)
{
do
{
dice = randomNumbers.nextInt(6) + 1;
System.out.println("You rolled: " + dice);
if(dice == 1)
{
turnScores = 0;
System.out.print("Your lose your turn!");
System.out.println("Your Total is " + totalScores);
break;
}
else
{
turnScores += dice;
System.out.print("Your turn score is " + turnScores);
System.out.println(" and your total scores is " + totalScores);
System.out.println("If you hold, you will have " + turnScores
+ " points.");
System.out.println("Enter 'r' to roll again, 'h' to hold.");
input = keyboard.nextLine();
repeat = input.charAt(0);
if(repeat == 'h')
{
break;
}
}
}
while(input.equalsIgnoreCase("r") || dice != 1);
totalScores += turnScores;
peppers = peppers(turnScores, turnScores2);
System.out.println("Your scores is " + totalScores);
turnScores = 0;
System.out.println();
System.out.println("It is the computer's turn.");
do
{
dice2 = randomNumbers.nextInt(6) + 1;
System.out.println("The computer rolled: " + dice2);
if(dice2 == 1)
{
turnScores2 = 0;
System.out.print("The computer lost its turn!");
System.out.println(" Computer total is " + totalScores2);
break;
}
else
{
turnScores2 += dice2;
if(turnScores2 >= 20 || (totalScores2 + turnScores2) >= 20 )
{
System.out.println("The computer holds");
break;
}
}
}
while(dice2 != 1 || turnScores2 < 20);
totalScores2 += turnScores2;
System.out.println("The computer's scores is " + totalScores2 + "\n");
turnScores2 = 0;
}
}
public static boolean peppers(int chili, int ghost)
{
boolean done;
done = true;
if(chili >= 20);
{
done = false;
System.out.println(" YOU WIN!!!");
return done;
}
else (ghost >= 20);
{
done = false;
System.out.println(" COMPUTER WINS");
return done;
}
/*else
{
return done;
}
*/
}
}
Try removing the semicolons in if(chili >= 20); and else (ghost >= 20);.
public static boolean peppers(int chili, int ghost)
{
boolean done;
done = true;
if(chili >= 20)
{
done = false;
System.out.println(" YOU WIN!!!");
}
else if (ghost >= 20)
{
System.out.println(" COMPUTER WINS");
}
return done;
}
replace
else (ghost >= 20);
with
else if (ghost >= 20)
and remove the semicolons after the if-statement.
Related
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
I am having trouble on a program and I can't seem to fix the problem. I have a team roster program that gives the option of replacing a player's number and rating, but when that option is used the loop keeps going and it won't end and go back to the menu for the other options. If anyone could help point me in the right direction it would be appreciated.
import java.util.Scanner;
class PlayerRoster {
public static void main(String[] args) {
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
int[] playerJerseyNumber = new int[5];
int[] playerRating = new int[5];
for (int i = 0; i < 5; i++) {
//Taking jersey number till it is in the range of 0-99
while (true) {
System.out.println("Enter player " + (i + 1)
+ "'s jersey number:");
playerJerseyNumber[i] = scanner.nextInt();
if (0 <= playerJerseyNumber[i] && playerJerseyNumber[i] <= 99) {
break;
} else {
System.out.println("Jersey number must be 0-99");
}
}
//Taking playerRating till it is in the range of 1-9
while (true) {
System.out.println("Enter player " + (i + 1) + "'s rating:");
playerRating[i] = scanner.nextInt();
if (1 <= playerRating[i] && playerRating[i] <= 9) {
break;
} else {
System.out.println("Player's ratings must be 1-9");
}
}
System.out.println("");
}
System.out.println("ROSTER");
//Displaying the rosters
for (int i = 0; i < 5; i++) {
System.out.println("Player " + (i + 1) + " -- Jersey number: "
+ playerJerseyNumber[i] + ", Rating: "
+ playerRating[i]);
}
System.out.println("");
//Printing the menu
do {
System.out.println("MENU " + "u - Update player rating");
System.out.println("a - Output players above a rating");
System.out.println("r - Replace player");
System.out.println("o - Output roster");
System.out.println("q - Quit");
System.out.println("");
System.out.println("Choose an option:");
char choice = scanner.next().charAt(0);
switch (choice) {
case 'u': {
System.out.println("Enter a jersey number:");
int playerJersey = scanner.nextInt();
System.out.println("Enter a new rating for player:");
int newRating = scanner.nextInt();
for (int i = 0; i < 5; i++) {
if (playerJerseyNumber[i] == playerJersey) {
playerRating[i] = newRating;
break;
}
}
}
break;
case 'a': {
System.out.println("Enter a rating:");
int aboveRating = scanner.nextInt();
System.out.println("ABOVE " + aboveRating);
for (int i = 0; i < 5; i++) {
if (playerRating[i] > aboveRating) {
System.out.println("Player " + (i + 1)
+ " -- Jersey number: "
+ playerJerseyNumber[i] + ", Rating: "
+ playerRating[i]);
}
}
}
break;
case 'r': {
boolean flag = true;
do {
System.out.println("Enter a jersey number:");
int newRating, playerNewJersey;
int playerJersey = scanner.nextInt();
for (int i = 0; i < 5; i++) {
if ((playerJerseyNumber[i] == playerJersey)) {
//Taking jersey number till it is in the range of 0-99
while (true) {
System.out.println("Enter a new jersey number:");
playerNewJersey = scanner.nextInt();
if (0 <= playerNewJersey && playerNewJersey <= 99) {
break;
} else {
System.out.println("Jersey number must be 0-99");
}
}
//Taking playerRating till it is in the range of 1-9
while (true) {
System.out.println("Enter a new rating for player:");
newRating = scanner.nextInt();
if (1 <= newRating && newRating <= 9) {
break;
} else {
System.out.println("Player's ratings must be 1-9");
}
}
playerJerseyNumber[i] = playerNewJersey;
playerJerseyNumber[i] = playerJersey;
playerRating[i] = newRating;
flag = false;
break;
}
}
if (!flag) {
System.out.println("Error: Invalid Jersey Number... Try Again...");
}
} while (flag);
}
break;
case 'o': {
System.out.println("ROSTER");
for (int i = 0; i < 5; i++) {
System.out.println("Player " + (i + 1)
+ " -- Jersey number: " + playerJerseyNumber[i]
+ ", Rating: " + playerRating[i]);
}
}
break;
case 'q':
break;
default:
break;
}
if (choice == 'q') break;
} while (true);
} catch (Exception e) {
}
return;
}
}
if (flag) {
System.out.println("Error: Invalid Jersey Number... Try Again...");
} }
Removing the ! solves the problem. Also, a few lines above it there is
playerJerseyNumber[i] = playerNewJersey;
playerJerseyNumber[i] = playerJersey;
I don't understand why you need to reassign it to playerJersey. This would cause the jersey number to not get updated.
Ok, so I have created the following program. It is not yet complete but when the code comes to the end (y or n part) and the user decides to try again they don't get the option to enter a new bet it just uses the one entered from the first time.
(Please comment if you need help about understanding the code or thinking it might be hard for other people to understand)
import java.util.*;
public class Lab15 {
static Scanner kin = new Scanner(System.in);
public static void main(String[] args) {
double money = 1000;
System.out.println("Welcom To Craps You Start With 1000$!!!");
int play = 1; //variable to cancel whole loop
char yesNo; //if user wants to continue playing or not
while(money > 0 && play == 1) {
System.out.print("Please Enter The Amount You Want To Bet: ");
double bet = kin.nextDouble();
while((bet <= money || bet > 0)) {
do { //loop to test if the bet is legit
if(money < bet || bet < 0) {
System.out.print("Sorry Invalid Bet; Please Enter A Legitimant Bet: ");
bet = kin.nextDouble();
}
} while(bet > money || bet < 0);
money -= bet;
System.out.println("You Have Bet $" + bet + " And Have " + money + " Left");
int die1 = (1 + (int) (6 * Math.random()));
int die2 = (1 + (int) (3 * Math.random()));
int sum = die1 + die2;
System.out.println("You Rolled " + die1 + " and " + die2 + " totaling " + sum);
System.out.print("Do You Want To Play Again(y) Or Not(n)");
yesNo = kin.next().charAt(0);
int loopBreak = 0; //to break do while loop bellow
do {
if(yesNo == 'y') { //take above yes no to restart loop or not
System.out.println("Restarting...");
loopBreak += 1;
continue;
}
else if(yesNo == 'n') {
System.out.println("Thank You For Playing");
play -= 1; //to cancel whole program
break;
}
else {
System.out.println("Please Enter 'y' Or 'n'");
}
} while(loopBreak == 0);
if(play == 0) {
break;
}
}
}
}
}
Its all about nested while loop don't stop when it needed. Its like this
while(money > 0 && play == 1) {
System.out.print("Please Enter The Amount You Want To Bet: ");
double bet = kin.nextDouble();
while((bet <= money || bet > 0)) {
...
do {
if(yesNo == 'y') { //take above yes no to restart loop or not
System.out.println("Restarting...");
loopBreak += 1;
continue;
}
else if(yesNo == 'n') {
System.out.println("Thank You For Playing");
play -= 1; //to cancel whole program
break;
}
else {
System.out.println("Please Enter 'y' Or 'n'");
}
} while(loopBreak == 0);
if(play == 0) {
break;
}
}
}
After you get answer 'y' you don't break the nested while and program never get the
while(money > 0 && play == 1) {
--> System.out.print("Please Enter The Amount You Want To Bet: ");
--> double bet = kin.nextDouble();
//because below while loop continues to loop
while((bet <= money || bet > 0)) {
...
}
}
part. Anyways corrected code is here(i tried every possibility and it worked)
import java.util.*;
public class Lab15 {
static Scanner kin = new Scanner(System.in);
public static void main(String[] args) {
double money = 1000;
System.out.println("Welcom To Craps You Start With 1000$!!!");
int play = 1; //variable to cancel whole loop
char yesNo; //if user wants to continue playing or not
while(money > 0 && play == 1) {
System.out.print("Please Enter The Amount You Want To Bet: ");
double bet = kin.nextDouble();
while((bet <= money || bet > 0)) {
do { //loop to test if the bet is legit
if(money < bet || bet < 0) {
System.out.print("Sorry Invalid Bet; Please Enter A Legitimant Bet: ");
bet = kin.nextDouble();
}
} while(bet > money || bet < 0);
money -= bet;
System.out.println("You Have Bet $" + bet + " And Have " + money + " Left");
int die1 = (1 + (int) (6 * Math.random()));
int die2 = (1 + (int) (3 * Math.random()));
int sum = die1 + die2;
System.out.println("You Rolled " + die1 + " and " + die2 + " totaling " + sum);
System.out.print("Do You Want To Play Again(y) Or Not(n): ");
yesNo = kin.next().charAt(0);
int loopBreak = 0; //to break do while loop bellow
do {
if(yesNo == 'y') { //take above yes no to restart loop or not
System.out.println("Restarting...");
loopBreak++;
continue;
}
else if(yesNo == 'n') {
System.out.println("Thank You For Playing");
play--; //to cancel whole program
break;
}
else {
System.out.println("Please Enter 'y' Or 'n': ");
}
} while(loopBreak == 0);
if(play == 0 || loopBreak == 1) {
break;
}
}
}
}
}
Have a good day!
Another solution is to use labeled breaks/continues https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
However it should be used sparingly (or not at all). You probably can simplify it in some other way.
package test.test;
import java.util.Scanner;
public class Lab15 {
static Scanner kin = new Scanner(System.in);
public static void main(String[] args) {
double money = 1000;
System.out.println("Welcom To Craps You Start With 1000$!!!");
int play = 1; // variable to cancel whole loop
char yesNo; // if user wants to continue playing or not
//Labeled <-----------------
start: while (money > 0 && play == 1) {
System.out.print("Please Enter The Amount You Want To Bet: ");
double bet = kin.nextDouble();
while ((bet <= money || bet > 0)) {
do { // loop to test if the bet is legit
if (money < bet || bet < 0) {
System.out.print("Sorry Invalid Bet; Please Enter A Legitimant Bet: ");
bet = kin.nextDouble();
}
} while (bet > money || bet < 0);
money -= bet;
System.out.println("You Have Bet $" + bet + " And Have " + money + " Left");
int die1 = (1 + (int) (6 * Math.random()));
int die2 = (1 + (int) (3 * Math.random()));
int sum = die1 + die2;
System.out.println("You Rolled " + die1 + " and " + die2 + " totaling " + sum);
System.out.print("Do You Want To Play Again(y) Or Not(n)");
yesNo = kin.next().charAt(0);
int loopBreak = 0; // to break do while loop bellow
do {
if (yesNo == 'y') { // take above yes no to restart loop or not
System.out.println("Restarting...");
loopBreak += 1;
//Labeled continue <-----------------
continue start;
} else if (yesNo == 'n') {
System.out.println("Thank You For Playing");
play -= 1; // to cancel whole program
break;
} else {
System.out.println("Please Enter 'y' Or 'n'");
}
} while (loopBreak == 0);
if (play == 0) {
break;
}
}
}
}
}
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Hangman {
public static void main(String[] args) {
String playAgainMsg = "Would you like to play again?";
String pickCategoryMsg = "You've tried all the words in this category!\nWould you like to choose another category?";
int winCounter = 0, loseCounter = 0, score = 0;
String[] words;
int attempts = 0;
String wordToGuess;
boolean playCategory = true, playGame = true;
int totalCounter = 0, counter;
while (playCategory && playGame)
{
while (playCategory && playGame) {
words = getWords();
counter = 0;
while (playGame && counter < words.length) {
wordToGuess = words[counter++];
if (playHangman(wordToGuess)) {
winCounter++;
System.out.println("You win! You have won " + winCounter + " game(s)." + " You have lost " + loseCounter + " game(s).");
} else {
loseCounter++;
System.out.println("You lose! You have lost " + loseCounter + " game(s)." + " You have won " + winCounter + " game(s).");
}
if (counter < words.length) playGame = askYesNoQuestion(playAgainMsg);
}
if (playGame) playCategory = askYesNoQuestion(pickCategoryMsg);
}
}
}
public static boolean playHangman(String wordToGuess) {
String[] computerWord = new String[wordToGuess.length()];
String[] wordWithDashes = new String[wordToGuess.length()];
for (int i = 0; i < computerWord.length; i++) {
computerWord[i] = wordToGuess.substring(i, i+1);
wordWithDashes[i] = "_";
}
Scanner in = new Scanner(System.in);
int attempts = 0, maxAttempts = 7;
boolean won = false;
int points = 0;
while (attempts < maxAttempts && !won) {
String displayWord = "";
for (String s : wordWithDashes) displayWord += " " + s;
System.out.println("\nWord is:" + displayWord);
System.out.print("\nEnter a letter or guess the whole word: ");
String guess = in.nextLine().toLowerCase();
if (guess.length() > 1 && guess.equals(wordToGuess)) {
won = true;
} else if (wordToGuess.indexOf(guess) != -1) {
boolean dashes = false;
for (int i = 0; i < computerWord.length; i++) {
if (computerWord[i].equals(guess)) wordWithDashes[i] = guess;
else if (wordWithDashes[i].equals("_")) dashes = true;
}
won = !dashes; // If there are no dashes left, the whole word has been guessed
} else {
drawHangmanDiagram(attempts);
System.out.println("You've used " + ++attempts + " out of " + maxAttempts + " attempts.");
}
}
int score = 0;
score = scoreGame(attempts);
System.out.println("Your score is: " + score);
return won;
}
//should take in a failure int from the main method that increments after every failed attempt
public static void drawHangmanDiagram(int failure)
{
if (failure == 0)
System.out.println("\t+--+\n\t| |\n\t|\n\t|\n\t|\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 1)
System.out.println("\t+--+\n\t| |\n\t| #\n\t|\n\t|\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 2)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| /\n\t|\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 3)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| / \\\n\t|\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 4)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| /|\\\n\t| |\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 5)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| /|\\\n\t| |\n\t| /\n\t|\n\t|\n\t+--");
else if (failure == 6)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| /|\\\n\t| |\n\t| / \\\n\t|\n\t|\n\t+--");
}
// Asks user a yes/no question, ensures valid input
public static boolean askYesNoQuestion(String message) {
Scanner in = new Scanner(System.in);
boolean validAnswer = false;
String answer;
do {
System.out.println(message + " (Y/N)");
answer = in.nextLine().toLowerCase();
if (answer.matches("[yn]")) validAnswer = true;
else System.out.println("Invalid input! Enter 'Y' or 'N'.");
} while (!validAnswer);
return answer.equals("y");
}
public static boolean askForCategory(int category) {
Scanner in = new Scanner(System.in);
boolean validAnswer = false;
String answer;
do {
System.out.println("\nWould you like to play again? (Y/N)");
answer = in.nextLine().toLowerCase();
if (answer.matches("[yn]")) validAnswer = true;
else System.out.println("Invalid input! Enter 'Y' or 'N'.");
} while (!validAnswer);
return answer.equals("y");
}
// Asks the user to pick a category
public static String[] getWords() {
String[] programming = {"java", "pascal", "python", "javascript", "fortran", "cobol"};
String[] sports = {"gymnastics", "badminton", "athletics", "soccer", "curling", "snooker", "hurling", "gaelic", "football", "darts"};
String[] result = {""};
Scanner in = new Scanner(System.in);
boolean validAnswer = false;
String answer;
do {
System.out.println("Pick a category:\n1. Programming\n2. Sports");
answer = in.nextLine().toLowerCase();
if (answer.matches("[1-2]")) validAnswer = true;
else System.out.println("Invalid input! Enter the number of the category you want.");
} while (!validAnswer);
int selection = Integer.parseInt(answer);
switch (selection) {
case 1: result = randomOrder(programming); break;
case 2: result = randomOrder(sports); break;
}
return result;
}
// Sorts a String array in random order
public static String[] randomOrder(String[] array) {
int[] order = uniqueRandoms(array.length);
String[] result = new String[array.length];
for (int i = 0; i < order.length; i++) {
result[i] = array[order[i]];
}
return result;
}
// Generates an array of n random numbers from 0 to n-1
public static int[] uniqueRandoms(int n) {
int[] array = new int[n];
int random, duplicateIndex;
for (int i = 0; i < n; ) {
random = (int) (Math.random() * n);
array[i] = random;
for (duplicateIndex = 0; array[duplicateIndex] != random; duplicateIndex++);
if (duplicateIndex == i) i++;
}
return array;
}
public static int scoreGame(int attempts)
{
int score = 0;
switch (attempts)
{
case 0: score = 70; break;
case 1: score = 60; break;
case 2: score = 50; break;
case 3: score = 40; break;
case 4: score = 30; break;
case 5: score = 20; break;
case 6: score = 10; break;
case 7: score = 0; break;
}
return score;
}
}
I have got it working so that it keeps count of the games won and lost, as well as assigning a score based on the amount of attempts/lives saved but I haven't been able to find a way to get it to keep a total score for all of the games played. Each game unfortunately has a seperate score. If anyone can advise me on a way of doing this, it would be greatly appreciated.
Create an int totalScore variable where winCounter, loseCounter and score are defined. Then increment it after each call to scoreGame()
score = scoreGame(attempts);
totalScore += score;
System.out.println("Your score is: " + score);
If you want to permanently save statistics between sessions then it's a whole nother story. You would need to write your scores to a file after each round and then start your program by reading this score file. It's hardly impossible, but requires a bit more code.
public static void main(String[] args) {
int money = 100, roll1, roll2;
int userBet;
char c;
int lostwin;
Scanner in = new Scanner(System.in);
do {
if (money == 0 || money < 0)
break;
System.out.println(" You have " + money + " dollars. ");
userBet = getBet(in, money);
if (userBet == 0)
break;
c = getHighLow(in);
roll1 = getRoll();
System.out.println(" Die 1 rolls : " + roll1);
roll2 = getRoll();
System.out.println(" Die 2 rolls : " + roll2);
System.out.println("Total of two dice is: " + (roll1 + roll2));
lostwin = determineWinnings(c, userBet, roll1 + roll2);
if (lostwin < 0)
System.out.println("You lost!");
else
System.out.println("You won " + lostwin + " dollars! ");
money = money + lostwin;
} while (true);
}
private static int getBet(Scanner inScanner, int moneyPot) {
System.out.println("Enter an amount to bet (0 to quit): ");
int result = inScanner.nextInt();
if (result > moneyPot) {
do {
System.out.println("Enter an amount to bet (0 to quit): ");
result = inScanner.nextInt();
} while (result > moneyPot);
}
return result;
}
private static char getHighLow(Scanner inScanner) {
System.out.println("High, low or sevens (H/L/S): ");
String str = inScanner.next();
return str.charAt(0);
}
private static int getRoll() {
return (int) (Math.random() * 6) + 1;
}
private static int determineWinnings(char highLow, int bet, int roll) {
int result = 0;
if (highLow == 'H') {
if (roll < 7) {
result = -1 * bet;
} else {
result = bet;
}
}
if (highLow == 'L') {
if (roll > 7) {
result = -1 * bet;
} else {
result = bet;
}
}
if (highLow == 'S') {
if (roll == 7) {
result = 4 * bet;
} else {
result = -1 * bet;
}
}
return result;
}
I need the program to say "Goodbye!" when the user enters the number 0, but I can't figure out where to put it or how to get it to work. The other issue I need help with is if the user enters a number higher than 100 or less than 1, the program needs to say "Your bet MUST be between 0 and 100 dollars". I don't know where to put them or how to get them to work.
You can modify your getBet function like this to achieve what you want.
private static int getBet(Scanner inScanner, int moneyPot) {
int result;
System.out.println("Enter an amount to bet (1-100) (0 to quit): ");
do {
result = inScanner.nextInt();
if (result == 0) {
System.out.println("Good Bye");
return result;
} else if (result < 0 && result > 100) {
System.out.println("Please enter an amount between (1-100) (0 to quit)");
} else if (result > moneyPot) {
System.out.println("Please enter an amount less than your moneyPot between (1-100) (0 to quit)");
} else {
return result;
}
} while (true);
}
public static void main(String[] args) {
int money = 100;
int roll1;
int roll2;
int userBet;
int lostwin;
char c;
Scanner in = new Scanner(System.in);
do {
if (money < 1)
break;
System.out.println(" You have " + money + " dollars. ");
userBet = getBet(in, money);
if (userBet == 0)
break;
c = getHighLow(in);
roll1 = getRoll();
System.out.println(" Die 1 rolls : " + roll1);
roll2 = getRoll();
System.out.println(" Die 2 rolls : " + roll2);
System.out.println("Total of two dice is: " + (roll1 + roll2));
lostwin = determineWinnings(c, userBet, roll1 + roll2);
if (lostwin < 0)
System.out.println("You lost!");
else
System.out.println("You won " + lostwin + " dollars! ");
money = money + lostwin;
} while (money > 0);
System.out.println("Goodbye!");
}
private static int getBet(Scanner inScanner, int moneyPot) {
int bet;
do {
System.out.println("Enter an amount to bet (0 to quit): ");
bet = inScanner.nextInt();
} while (bet > moneyPot && bet != 0);
return bet;
}
private static char getHighLow(Scanner inScanner) {
System.out.println("High, low or sevens (H/L/S): ");
String str = inScanner.next();
return str.charAt(0);
}