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.
Related
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'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.
I need help validating input. I have a program that works with student grades based off user input. if someone enters grades below 0 or over 100 I want this loop to restart. Here is what I have so far:
double scores[] = new double[size];
for (int i = 0;i<= scores.length-1;i++)
{
System.out.print("\n\nScore number " + (i+1) + ": ");
scores[i] = sc.nextInt();
}
System.out.println("Here are your scores: " + Arrays.toString(scores));
I'm confused on how to implement invalid checker. I know it has something to do with a while loop. such as while a value is 0, and if someone enters invalid answer it will change from 0. But not sure how exactly I should do this, or if theres a better way
Any help appreciated. thanks
You can make use of a nested while loop and conditional statement for this:
for (int i = 0;i< scores.length;i++){
while(true){
System.out.print("\n\nScore number " + (i+1) + ": ");
int score = sc.nextInt();
if(score >= 0 && score <=100){
scores[i] = score;
break;
}else{
System.out.println("Error: score entered is outside allowable range");
System.out.println("Please try again");
continue;
}
}
}
You can simply ask the user to re-enter the value of the score which has been entered wrong.
double scores[] = new double[size];
for (int i = 0; i<= scores.length-1; i++)
{
System.out.print("\n\nScore number " + (i+1) + ": ");
scores[i] = sc.nextInt();
if(scores[i] < 0 || scores[i] > 100) {
i -= 1;
continue;
}
}
I'm confused on how to implement invalid checker. I know it has something to do with a while loop.
do-while loop is preferred in input validation because it allows input to be received first, then check if it passes the requirement. If input is invalid, repeat.
for(int i=0; i<scores.length; i++){
do{
System.out.print("\n\nScore number " + (i+1) + ": ");
input = sc.nextInt();
}while(input < 0 || input > 100);
scores[i] = input;
}
The for-loop and do-while loop serve different purpose. Hence, do not be confused by the
- for-loop which is only responsible to receive multiple inputs for the array and the
- while loop which is only responsible for validating every single input.
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!
Here is the assignment:
For this program, there are two "parts". The first part will run the trials and determine how many caps each trial opens before finding a winning cap. Every trial (person) will be a winner. The number of caps opened by each trial is written to the file.
The second part of the program will read in the values and calculate the average. The average should be between 4.5 and 5.5 since there is a 1 in 5 chance of winning.
It compiles and runs, but the average is always 0.
My code:
int randNum = 0;
Random randNumList = new Random();
int counter = 0;
Scanner in = new Scanner(System.in);
System.out.println("How many trials will there be?");
int trials = in.nextInt();
int winner = 0;
PrintWriter outFile = new PrintWriter (new File("cap.txt"));
//run trials
for (int loop = 1; loop <= trials; loop++)
{
//select random number until 5 is selected
randNum = randNumList.nextInt(6);
for (randNum = randNumList.nextInt(6); randNum == 5; randNum++)
{
randNum = randNumList.nextInt(6);
counter++;
}
outFile.println(loop + " " + randNum);
}
outFile.close ( ); //close the file when finished
String token = " ";
Scanner inFile = new Scanner(new File("cap.txt"));
while (inFile.hasNext())
{
token = inFile.next();
if(token.equals("5"))
winner++;
}
double average = winner/counter;
System.out.println("The average number is " + average);
Apart from the int/int division accuracy problem which should be winner/(double)counter or (double)winner/counter try changing your inner for loop to a do while. In general, prefer while when you don't know the exact number of iterations.
Also, randNumList.nextInt(6) is [0-5], thus there are 6 possible outcomes -> there is a 1 in 6 chance of winning. To correct this, use randNumList.nextInt(5) + 1
for (int loop = 1; loop <= trials; loop++) {
//select random number until 5 is selected
do {
randNum = randNumList.nextInt(5) + 1;
counter++;
} while (randNum != 5);
outFile.println(loop + " " + randNum); //why here?? maybe you should add it below counter++;
}
also if(token.equals("5")) won't work, as you write (loop + randNum), it should work if you use outFile.println(randNum);
Your cap.txt file doesn't contain "5" => winner = 0 and average = 0/counter = 0 (always).
winner/counter returns an int not a double (integer division because both operands are integer so the result is truncated). Try this:
winner/(double)counter
That does return a double.