I'm creating a gambling application with 2 games. However I want to be able to switch from one game to the next. I tried if(game == 1), but it seemed that once I matched the condition, it exited the loop and trying to take input again would not switch to the second game. Then I tried do while but even when I set my input to "2" it still starts game #1. Any suggestions on what I should do?
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;
double bet1 = 0;
double bet2 = 0;
String kBet = null;
//Call method gameChoice to allow player to choose what game they want to play.
gameChoice();
int game = input.nextInt();
do {
System.out.println("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-BLACK JACK-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-");
System.out.print("Please choose Black or Red, and a number from 1-10..(Example: Red 4): ");
String color = input.next();
int number = input.nextInt();
//Seperate bets for color and number. Bet1 = color bet, bet2 = number bet
System.out.print("Your available balance is $"+balance+". How much would you like to bet on "+color+"?");
bet1 = input.nextInt();
if(bet1 > balance) {
System.out.print("You dont have enough money to bet $"+bet1+". Please enter a valid bet: $");
bet1 = input.nextInt();
}
else
balance -= bet1;
double profit1 = (bet1 * 2) - bet1;
//Bet 2 for number.
System.out.print("Your available balance is $"+balance+". How much would you like to bet on "+number+"?");
bet2 = input.nextInt();
if(bet2 > balance) {
System.out.print("You dont have enough money to bet $"+bet2+". Please enter a valid bet: $");
bet2 = input.nextInt();
}
else
balance -= bet2;
double profit2 = (bet2 * 5) - bet2;
//Give bet info
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-------------------------------------");
//Generate random number, Generate random color.
Random rouletteNum = new Random();
int rNum = min + rouletteNum.nextInt(max);
int rCol = min + rouletteNum.nextInt(colmax);
//Only generate 2 numbers between 1-2; 1 is black, 2 is red.
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);
}
//All possible conditions for betting outcomes.
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("------------------------------------------------------------------------");
//Call isBroke method to check if player is bankrupt.
if(isBroke(balance) == true) {
endGame(balance);
}
else {
//If player isn't bankrupt, ask if they want to place another bet.
System.out.println("New balance: $"+balance);
gameChoice2();
game = input.nextInt();
}
}
while(game == 1);
{
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();
//check if bet amount is greater then the balance.
if(bet > balance) {
System.out.print("You dont have enough money to bet $"+bet+". Please enter a valid bet: $");
bet = input.nextInt();
}
else
System.out.println("--------------------------------------------------------------------------");
System.out.println("Round is beginning.........");
for(int i =0; i < stopGame; i++) {
//Do while to keep the numbers generating until i == 1 (until crash)
do {
//Generate random number from 1-100, if the number is less than 98, print the digit (Example : 1.34)
int crash =(int)(Math.random() * 100);
if (crash < 98) {
start += .01;
System.out.printf("%.2f\n",start);
}
//if random number from 1-100 is greater than 98, crash the game.
else if(crash > 98) {
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);
}
//Check if player cashed out before game crashed.
if(cashout < crashValue) {
System.out.println("Congrats! You cashed out at "+cashout+" before the game crashed. You've won $"+bet*cashout);
balance += bet * cashout;
}
//Player didn't cash out in time, and lost.
else {
System.out.println("Sorry! The game crashed before you could cash out. You've lost $"+bet);
balance -= bet;
}
System.out.println("------------------------------------------------------------------------");
//check if player is bankrupt.
if(isBroke(balance) == true) {
endGame(balance);
}
else {
//If they arent bankrupt, ask if they want another bet.
System.out.println("New balance: $"+balance);
gameChoice2();
game = input.nextInt();
}
}
while(game == 2);
}
You've used a do...while loop. This type of loop always executes its body at least once before evaluating the while condition.
Related
Trying to make the user keep inputting correct integers between 2 sets of values, but for example if the user inputs a wrong integer, then the while loop skips and runs onto the next code in my program. If anyone could point out how I can make the user repeat the question at each step if they get it wrong, would appreciate it.
System.out.print("How many asteroids: ");
int asteroid = input.nextInt();
while (asteroid > 0) {
System.out.print("x location of the asteroid (between 1-950 pixels): ");
double asteroidLocationX = input.nextDouble();
if (asteroidLocationX >= 1 && asteroidLocationX <= 950) {
System.out.print("y location of the asteroid (between 150-550 pixels): ");
double asteroidLocationY = input.nextDouble();
if (asteroidLocationY >= 150 && asteroidLocationY <= 550) {
System.out.print("Width of the asteroid (min: 30 pixels, max: 50 pixels): ");
double asteroidSizeWidth = input.nextDouble();
if (asteroidSizeWidth >= 30 && asteroidSizeWidth <= 50) {
System.out.print("Height of the asteroid (min: 30 pixels, max: 50 pixels): ");
double asteroidSizeHeight = input.nextDouble();
if (asteroidSizeHeight >= 30 && asteroidSizeHeight <= 50) {
gc.setFill(Color.ALICEBLUE);
gc.fillOval(asteroidLocationX, asteroidLocationY, asteroidSizeWidth, asteroidSizeHeight);
} else
System.out.println("Wrong input, try again");
} else
System.out.println("Wrong input, try again");
}else
System.out.println("Wrong input, try again");
} else
System.out.println("Wrong input, try again");
asteroid--;
}
You need to re-ask the question if there's a problem with the answer
double val = -1;
do {
System.out.println("Enter a number between 1 and 10");
val = input.nextDouble();
while (input >= 1 && input <= 10);
I have the while loop running and processing properly. When the numbers that the user entered do not match the random number, the code prints out "Sorry ...(and proceeds to explain what the right number is)" each time the user is wrong. However, I cannot get the code to print out those same exact random numbers at the very end of the last loop before it terminates. Any suggestions?
while (counter < 6)
{
counter++;
System.out.println("Enter a number between 1-60: ");
userInput = scan.nextInt();
if (userInput > 60 || userInput < 1)
System.out.println("Invalid input");
int randomNumber = (int) (Math.random() * 60) + 1;
if (userInput == randomNumber)
System.out.println("Congrats, you have won!");
else
System.out.println("Sorry, you didn't choose the winning number." + "The winning number is " + randomNumber + ".");
}
The bottom of the code has the winning number, but I want all of those same exact random numbers (which were randomized earlier) to show up at the end of the sixth loop. Also, the order of the user input does not influence the results. If the user chooses 1-13-8-34-56-2 and the computer had come up with 1-8-56-2-14-34…there would still be 5 matching numbers
otherwise you can store them in a string variable after casting them to string by doing this
String randomNums = "";
randomNums += randomNums +" - "+ String.ValueOf(randomNumber);
Here is the piece of code,
Just keep concating the random numbers with a string variable
import java.util.Scanner;
public class RandomNumbers{
public static void main(String []args){
int counter =0;
int userInput=0;
String userEntries="";
String randomEntries="";
Scanner scan=new Scanner(System.in);
while (counter < 6)
{
counter++;
System.out.println("Enter a number between 1-60: ");
userInput = scan.nextInt();
if (userInput > 60 || userInput < 1)
System.out.println("Invalid input");
int randomNumber = (int) (Math.random() * 60) + 1;
if (userInput == randomNumber)
System.out.println("Congrats, you have won!");
else
System.out.println("Sorry, you didn't choose the winning number." + "The winning number is " + randomNumber + ".");
userEntries+=userInput+ ((counter < 5) ? "-" : "");
randomEntries+=randomNumber+((counter < 5) ? "-" : "");
}
System.out.println(userEntries);
System.out.println(randomEntries);
}
}
OUTPUT:
Enter a number between 1-60:
Sorry, you didn't choose the winning number.The winning number is 28.
Enter a number between 1-60:
Sorry, you didn't choose the winning number.The winning number is 39.
Enter a number between 1-60:
Sorry, you didn't choose the winning number.The winning number is 13.
Enter a number between 1-60:
Sorry, you didn't choose the winning number.The winning number is 13.
Enter a number between 1-60:
Sorry, you didn't choose the winning number.The winning number is 8.
Enter a number between 1-60:
Sorry, you didn't choose the winning number.The winning number is 42.
1-2-3-4-56
28-39-13-13-842
i think it would be something like this, since you do not want store the numbers in an array or array list, you will have to work with string concatenation.
string keepValue="";
while (counter < 6)
{
counter++;
System.out.println("Enter a number between 1-60: ");
userInput = scan.nextInt();
if (userInput > 60 || userInput < 1)
System.out.println("Invalid input");
int randomNumber = (int) (Math.random() * 60) + 1;
keepValue=keepValue+randomNumber+"-";
if (userInput == randomNumber)
System.out.println("Congrats, you have won!");
else
System.out.println("Sorry, you didn't choose the winning number." + "The
winning number is " + randomNumber + ".");
}
System.out.println(keepValue.substring(0, keepValue.length() - 1));
i hope this gives you an idea on how to solve it
I am stuck in a short program I've been working on. I need to find a way to store the best score (the lowest score) after the user has run the game multiple times. Here is the code for my program-
import java.util.*;
import java.util.Random;
import java.util.Scanner;
public class GuessingGame
{
public static void main(String[] args){
Random rand = new Random();
Scanner prompt = new Scanner(System.in);
String play = "";
boolean playAgain = true;
int playTimes = 0;
int lowScore = 0;
int count = 0;
do{
int target = rand.nextInt(100) + 1;
System.out.print("\nEnter a number between 1 and 100: ");
int guess = prompt.nextInt();
while(guess != target){
if(target > guess){
System.out.println("The number is higher. Try again.");
count++;
}
else{
System.out.println("The number is lower. Try again.");
count++;
}
System.out.print("Enter a number between 1 and 100: ");
guess = prompt.nextInt();
}
System.out.println("You guessed correctly! Congratulations!");
count++;
System.out.println("Your score is: " + count);
System.out.print("\nWould you like to play again? Yes or no?: ");
play = prompt.next();
if(play.equalsIgnoreCase("no")){
playAgain = false;
}
else if(play.equalsIgnoreCase("yes")){
count = 0;
playAgain = true;
}
playTimes++;
if(count < lowScore){
lowScore = count;
}
}while(playAgain);
System.out.println("\nGame Summary");
System.out.print(" Games played: " + playTimes);
System.out.println("\n Best Score: " +lowScore);
The issue is that I've been running this program and the "best score" keeps displaying 0. I've tried bringing my "if" statement outside of the while-loop but it continues displaying 0. Could anyone help with my logic?
count is initialized to be 0 and is only incremented, so it won't be negative unless overflow occurs.
lowScore is initialized to be 0 and any non-negative numbers are not less than, so count < lowScore has too little chance to be true.
You should initialize lowScore to Integer.MAX_VALUE or introduce a variable to remember if lowScore has a valid score like this:
int lowScore = 0;
int count = 0;
boolean isLowScoreValid = false; // the variable
if(!isLowScoreValid || count < lowScore){ // update if any value were't set
lowScore = count;
isLowScoreValid = true; // now a value is set
}
System.out.println("\n Best Score: " +(isLowScoreValid ? lowScore : "(none)"));
You need to initalize lowScore to the highest integer possible. Try
int lowScore = Integer.MAX_VALUE; and then run your program. Cheers!
Currently I am working on a program in which the user enters a value in cents (so $1.25 would be 125), and the program determines how many coins are given in the fewest amount. I have this working.
What is troubling me is that my professor wants the program to continuously loop until the user enters a value less than 0. I don't know how to do this because every time I try, it only ends up looping once and not displaying the proper amount of coins.
Please help.
Here is my code:
import java.util.Scanner;
public class MakingChange {
public static void main(String[] args) {
//Prompts user to input the change they recieved.
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the amount of change you recieved in coin format. Example: $1.25 would be entered as 125.");
int Change = sc.nextInt(); //The value is then stored as an integer named Change.
int Pennies = 0;
int Nickels = 0;
int Dimes = 0;
int Quarters = 0;
while (Change < 1){
System.out.println("Error: Cannot enter a value less than 1!");
//System.exit(0); //found at http://codingforums.com/java-jsp/69296-%5Bjava%5D-how-end-program.html
}
while (Change > 0){ //Runs a loop which determines how many of each coin is used by subtracting the values of the largest first and continuing until 0.
if (Change >= 25){
Change -= 25;
Quarters++;
}
else if (Change >= 10){
Change -= 10;
Dimes++;
}
else if (Change >= 5){
Change -=5;
Dimes++;
}
else if (Change >= 1){
Change -= 1;
Pennies++;
}
}
System.out.println("In total, you should have recieved:");
System.out.printf("Number of Quarters: %3d %n", Quarters);
System.out.printf("Number of Dimes: %6d %n", Dimes);
System.out.printf("Number of Nickels: %4d %n", Nickels);
System.out.printf("Number of Pennies: %4d %n", Pennies);
//Prints out final number of coins used by type of coin.
}
}
Scrap your first while loop. You don't want two loops handling the same thing. Next, initialize your "Change" variable, but move sc.nextInt(); inside so that it gets the input every iteration. Finally, make the loop a do-while loop so it runs at least once (alternatively you could initialize change to 1).
int Change = 0;
do{
Change = sc.nextInt();
// ...
}
while(Change > 0);
You need to ask the user how much change they get in the loop. Here is some code below:
import java.util.scanner;
public void MakingChange {
public static void main(String[] args) {
int change = 0;
int currentchange = 0;
Scanner in = new Scanner(System.in);
do {
change += currentchange;
System.out.println("Enter an amount of change.");
currentchange = in.nextInt();
} while(currentchange > 0);
}
}
System.out.println("Total change: " + change);
+1 To Gary for do loop idea.
You get the point.
I see a few issues in your code, Java naming conventions have variables start with a lower case letter. Next, you could simply loop while the Scanner.hasNextInt(). Then, your code would seem to be simpler if you counted the quarters, dimes and nickels (which your nickel counter counts as dimes) in their own loops. So, something like -
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String msg = "Please enter the amount of change "
+ "you received in coin format. Example: "
+ "$1.25 would be entered as 125.";
System.out.println(msg);
while (sc.hasNextInt()) {
int change = sc.nextInt();
int pennies = 0;
int nickels = 0;
int dimes = 0;
int quarters = 0;
if (change < 1) {
System.out.println("Error: Cannot enter a value less than 1!");
} else {
while (change >= 25) {
change -= 25;
quarters++;
}
while (change >= 10) {
change -= 10;
dimes++;
}
while (change >= 5) {
change -= 5;
nickels++;
}
pennies = change;
}
System.out.println("In total, you should have recieved:");
System.out.printf("Number of Quarters: %3d %n", quarters);
System.out.printf("Number of Dimes: %6d %n", dimes);
System.out.printf("Number of Nickels: %4d %n", nickels);
System.out.printf("Number of Pennies: %4d %n", pennies);
System.out.println(msg);
}
}
I would simplify your loop like so:
int change;
while ((change = sc.nextInt()) >= 0) {
//do code
}
Note the lowercase change, due to Java naming conventions.
The main problem with your code as-is is that you have two loops, and you'll exit the first immediately if your number is not less than 1 (or loop infinitely if it is less). You did the verification once, then did your program logic. Try using a single loop.
you need a loop around everything. The top of the loop will prompt and read the value, and the bottom of the loop will print the output. But because it is a loop, it will go back and prompt again. You don't have a loop at that level in the code as given.
import java.util.Scanner;
public class MakingChange {
public static void main(String[] args) {
//Prompts user to input the change they recieved.
Scanner sc = new Scanner(System.in);
int input = 0;
do{
System.out.println("Please enter the amount of change you recieved in coin format. Example: $1.25 would be entered as 125.");
input= sc.nextInt(); //The value is then stored as an integer named Change.
if(input<=0) {
System.out.println("Good Bye");
break; breaks the loop
}
else{
Change=input;
int Pennies = 0;
int Nickels = 0;
int Dimes = 0;
int Quarters = 0;
while (Change > 0){ //Runs a loop which determines how many of each coin is used by subtracting the values of the largest first and continuing until 0.
if (Change >= 25){
Change -= 25;
Quarters++;
}
else if (Change >= 10){
Change -= 10;
Dimes++;
}
else if (Change >= 5){
Change -=5;
Dimes++;
}
else if (Change >= 1){
Change -= 1;
Pennies++;
}
}
System.out.println("In total, you should have recieved:");
System.out.printf("Number of Quarters: %3d %n", Quarters);
System.out.printf("Number of Dimes: %6d %n", Dimes);
System.out.printf("Number of Nickels: %4d %n", Nickels);
System.out.printf("Number of Pennies: %4d %n", Pennies);
//Prints out final number of coins used by type of coin.
}//end of else
}while(input>0);//end of do while
}
Just make one while loop and keep referring to it until input < 0. So technically, all your calculations should go inside this huge while loop
I have an application a number guess game, users have to guess a number between 0 and 100, when they guess right the program asks them if they would like to play again when their done play I display the least number of guesses in a game and the greatest number of guess in a game. Right now all i get is the sum of all their guesses in the when using the "Math.min(,)"?
How do I get the minimum function to work??? the function code is in further below.
leastNumGuesses = Math.min(leastNumGuesses,guesses);
double rightNum = Math.random() *100;
int randomNum = (int) rightNum; //convert the random number to int
int tries = 0; //single game gussess output
int numberOfGames = 0;
int allTries = 0; //accumalates all tries(sum of all tries)
int guesses = 0; // guesses of all games combined
int gameGuesses = 0;
int leastNumGuesses = 100;
int mostNumGuesses = 0;
while (choice.equalsIgnoreCase("y"))
{
System.out.println();
int guess = getIntWithinRange(sc,"Enter the Number: ", 0, 100);
tries++;
guesses++;
gameGuesses++;
if (guess == randomNum)
{
numberOfGames++;
System.out.println("You got it in " + tries + " tries.");
leastNumGuesses = Math.min(leastNumGuesses,gameGuesses);
if (tries <=3)
System.out.println("Great work! You are a mathematical wizard.");
else if (tries > 3 && tries <= 7)
System.out.println("Not too bad! You've got some potential.");
else if (tries > 7)
System.out.println("What took you so long? Maybe you should take some lessons.");
System.out.println();
System.out.println("Would you like to play again (y/n):");
choice = sc.nextLine();
while (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y"))
{
System.out.println("Error! entry must be \"y\" or \"n\".");
System.out.println("Would you like to play again (y/n):");
choice = sc.nextLine();
}
if (choice.equalsIgnoreCase("y"))
{ // reset the random number & tries
rightNum = Math.random() *100;
randomNum = (int) rightNum;
tries=0;
gameGuesses++;
}
else if (choice.equalsIgnoreCase("n"))
{
allTries += guesses;
int averageNumGuess = allTries / numberOfGames;
System.out.println("Bye - Come back again");
System.out.println("Number of Games Played: " + numberOfGames);
System.out.println("Average Number of Guesses: " + averageNumGuess);
System.out.println("Least Amount of Guesses In a Single Game: " + leastNumGuesses);
}
}
It seems that you're changing what you want guesses to stand for in the middle of the program.
Remember that guesses is the total number of guesses over all games played, and that leastNumGuesses is initially set to 100. In most cases, you will find that guesses < leastNumGuesses, and thus the Math.min(guesses, leastNumGuesses) function will return guesses.
To fix: use variable other than guesses, for example, gameGuesses to keep track of how many guesses were made in a game. Then, Math.min(,) will behave as you expect.