So I am more or less completely done with this code that runs a guessing game. At the end it prints the total results for all games played. This includes total games, total guesses, avg guesses/game and the best score. I have it all worked out except i need the avg guesses/game to show 1 decimal place but the System.out.printf("Guesses/game = %.1f") isn't working and idk why
import java.util.*; //so I can use scanner
public class GuessingGame {
public static void main(String[] args) {
Random rand = new Random ();
int max = 100;
Scanner input = new Scanner(System.in);
int guess;
boolean play = true;
int totalGames = 0;
int totalGuesses = 0;
int bestGame = Integer.MAX_VALUE;
System.out.println("Can you guess the word?");
System.out.println("I am sure you cannot guess!");
System.out.println("Go ahead and try!");
System.out.println();
while (play) { //repeats until user enters a statement besides y when asked to play again
System.out.println("I'm thinking of a number between 1 and " + max + "...");
int numberToGuess = rand.nextInt(max) + 1;
int numberOfTries = 0;
boolean win = false;
while (!win) {
System.out.print("Your guess? ");
guess = input.nextInt();
numberOfTries++;
if (guess == numberToGuess) {
win = true;
} else if (guess > numberToGuess) {
System.out.println("It's lower.");
} else if (guess < numberToGuess) {
System.out.println("It's higher.");
}
input.nextLine();
}
if (numberOfTries == 1) {
System.out.println("You got it right in " + numberOfTries + " guess!");
} else {
System.out.println("You got it right in " + numberOfTries + " guesses!");
}
totalGames++;
totalGuesses+= numberOfTries;
System.out.print("Do you want to play again? ");
String answer = input.nextLine();
char firstLetter = answer.charAt(0);
if (firstLetter == 'y' || firstLetter == 'Y') {
play = true;
} else {
play = false;
bestGame = Math.min(bestGame, numberOfTries);
}
System.out.println();
}
System.out.println("Overall results:");
System.out.println("Total games = " + totalGames);
System.out.println("Total guesses = " + totalGuesses);
System.out.printf("Guesses/game = ", totalGuesses/totalGames);
System.out.println("Best game = " + bestGame);
}
}
both totalGuesses and totalGames are integers, so when you divide them you get an integer, whereas %f needs a floating point number.
Instead cast one to a floating point number for floating point division:
totalGuesses/(double)totalGames
Try a decimal formatter if for some reason you're simply getting the wrong output:
DecimalFormat formatter = new DecimalFormat("#.#");
System.out.println(formatter.format(avgGuesses)); //or whatever your var name is
Related
I am in an intro to the java class, and for one of my assignments, I have to use a loop (for or while) to keep track of scores between myself and the computer.
Here is the exact word for word instructions from my professor:
Write a program that does this: You (as a programmer) are the dealer.
pick a random number for yourself (between 0 - 100). Ask the user to input a random number (between 0 - 100) Whoever is closer to 21 wins the game.
(part 2) -Loop (keeping a counter) rite the same program and keep it going so that it keeps playing (dealing hands and saying who wins) until the user enters 21 at which point you print out some stats and say goodbye. For example, your goodbye might look like this:
Number of rounds played: 5
Dealer won: 3
Player won:2
you're 2 for 5.
Now I have written the code and played around it for hours and hours, and cannot make it work with a loop. I've tried while, do while, and for. I have looked everywhere on the internet for similar examples but cannot make a loop work in my program whatsoever. If anyone has any suggestions I would sure appreciate the feedback.
my code:
import java.util.*;
class asd {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome Valued player, take your guess!");
int min = 0;
int max = 100;
int input;
int c = 21;
int count = 0;
int userscore = 0;
int dealerscore = 0;
int gamesplayed = 0;
Random rand = new Random();
int r = rand.nextInt(max - min) + min;
input = sc.nextInt();
System.out.println("computer's number:" + r);
if (Math.abs(input - c) <= Math.abs(r - c)) {
System.out.println("the winner is the user!" + input);
dealerscore++;
gamesplayed++;
} else {
System.out.println("the winner is the computer!" + r);
userscore++;
gamesplayed++;
}
if (input == c) {
System.out.println("thank you for playing. you won.");
}
if (r == c) {
System.out.println("Thank you for playing:" + userscore);
System.out.println(userscore);
}
if (input == 0) {
System.out.println("Number of hands played:" + gamesplayed);
System.out.println("Dealer won:" + dealerscore);
System.out.println("User won:" + userscore);
}
while (input != c && r != c)
gamesplayed++;
}
// TODO code application logic here
}
Everything works fine, but I can't get the loop to work anywhere here.
You need a while loop that contains your game logic. The condition should just check if the input != c.
Then inside the loop, keep asking the user for input. Also, you mixed up userscore and dealerscore when adding the score.
Then at the end, once you come out of the loop, you can print the scores/stats.
Please read the comments below:
import java.util.*;
public class MyClass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome Valued player, take your guess!: ");
int min = 0;
int max = 100;
int input;
int c = 21;
int count = 0;
int userscore = 0;
int dealerscore = 0;
int gamesplayed = 0;
Random rand = new Random();
int r = rand.nextInt(max - min) + min;
input = sc.nextInt();
/*
This loop runs the game until the user enters 21
*/
while (input != c) {
System.out.println("Computer's number:" + r);
if (Math.abs(input - c) <= Math.abs(r - c)) {
System.out.println("The winner is the user! " + input);
userscore++; //You mixed up userscore and dealerscore
} else {
System.out.println("The winner is the computer! " + r);
dealerscore++; //You mixed up userscore and dealerscore
}
/*
User needs to keep entering guesses
*/
System.out.println();
System.out.println("Enter another guess: ");
r = rand.nextInt(max - min) + min;
input = sc.nextInt();
}
/*
You don't need any conditions since the games have already ended
But it should be outside and after the loop
*/
System.out.println("Number of hands played:" + gamesplayed);
System.out.println("Dealer won:" + dealerscore);
System.out.println("User won:" + userscore);
}
}
Change the loop with
while (input != c && r != c){
gamesplayed++;
System.out.println("Games played: " + gamesplayed );
}
you will see it is working. I would format the code better to debug it easier and always use the brackets.
Try this. Just refer to the code for explanations.
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome Valued player, take your guess!");
System.out.println("");
int min = 0;
int max = 100;
int input;
int c = 21;
int userscore = 0;
int dealerscore = 0;
int gamesplayed = 1;
Random rand = new Random();
while (true) { // so that the game will keep playing
System.out.println("----------------- ROUND " + gamesplayed + " -----------------");
int r = rand.nextInt(max - min) + min; // computer's choice
while (true) { // so that it will keep asking the user in case the user enters an invalid input
try {
System.out.print("Enter a random number! :");
input = Integer.parseInt(sc.nextLine());
break;
} catch (Exception e) {
System.out.println("Invalid input!");
}
}
System.out.println("The computer's random number is " + r);
// checking for the rounds winner
if (Math.abs(input - c) <= Math.abs(r - c)) {
System.out.println("The winner is the user!");
userscore++;
} else {
System.out.println("The winner is the computer!");
dealerscore++;
}
if (input == c) { // checking for ending the game
System.out.println("================ GAME STATS ================");
System.out.println("Thank you for playing.");
System.out.println("Number of hands played: " + gamesplayed);
System.out.println("Dealer score: " + dealerscore);
System.out.println("User score: " + userscore);
System.out.println("You are " + userscore + " out of " + gamesplayed + "!");
System.out.println("============================================");
sc.close();
break;
}
gamesplayed++; // increment games played
System.out.println("--------------------------------------------");
}
}
}
I have a problem with my program.
Program is a HILO game which requires the user to guess a number between a range of a generated number.
The problem is that once i press 0 on my keyboard, it reveals the random number, and essentially must end the loop and ask whether the user wants to continue or end the program. Instead, it continues the loop, and whenever I press a letter on the keyboard it shows me an Exception error which describes and input Miss Match. Can some one guide me on how to fix it?, maybe I wrote the program wrong, I tried multiple ways, it still doesn't work as it supposed to work.
Thank you.
import java.util.Scanner;
import java.util.Random;
import java.lang.Math;
public class HILOGAME
{
public static void firstGame()
{
final int range = 50;
int answer = 0;
int guesses;
int number;
int guessNum = 0;
String choice = "";
boolean Loop = false;
Scanner input = new Scanner(System.in);
Random r = new Random();
answer = r.nextInt(range) + 1;
System.out.println("IF YOU WISH TO GIVE UP, PRESS 0 ON THE KEYBOARD");
while (!Loop)
{
for (int exit = 0; exit < 10; exit++)
{
System.out.print("Guess a number between 1 and " + range + " : ");
number = input.nextInt();
guessNum = guessNum++;
guessNum += 1;
if (number == answer)
{
System.out.println(" Your guess was correct ");
System.out.println();
System.out.println("The number was: " + answer);
System.out.println("You guess the number with: " + guessNum + " guesses ");
System.out.println();
System.out.println("Enter x to continue to play or y to endgame");
choice = input.nextLine();
if (!choice.equalsIgnoreCase("x"))
{
Loop = true;
answer = r.nextInt(range) + 1;
System.out.print("A new number");
break;
}
else if (choice.equalsIgnoreCase("y"))
{
Loop = false;
System.out.print("END OF GAME");
exit = 11;
}
}
if (number > answer)
{
System.out.println("TOO HIGH");
}
if (number < answer)
{
System.out.println("TOO LOW");
}
if (number == 0)
{
System.out.println("YOU GAVE UP. THE NUMBER WAS " + answer);
System.out.println("Enter x to continue to play or y to endgame");
}
}
}
}
}
EDIT 1:
This code is working perfectly for me i have tried running it:
final int range = 50;
int answer = 0;
int guesses;
int number;
int guessNum = 0;
String choice = "";
boolean Loop = false;
Scanner input = new Scanner(System.in);
Random r = new Random();
answer = r.nextInt(range) + 1;
System.out.println("IF YOU WISH TO GIVE UP, PRESS 0 ON THE KEYBOARD");
while (!Loop)
{
int exit;
for (exit = 0; exit < 10; exit++)
{
System.out.print("Guess a number between 1 and " + range + " : ");
number = input.nextInt();
guessNum = guessNum++;
guessNum += 1;
if (number == answer)
{
System.out.println(" Your guess was correct ");
System.out.println();
System.out.println("The number was: " + answer);
System.out.println("You guess the number with: " + guessNum + " guesses ");
System.out.println();
System.out.println("Enter x to continue to play or y to endgame");
choice = input.next();
// HERE YOU ARE DOING THE WRONG THING
// What is the meaning of "not(!)" here ? !choice.equalsIgnoreCase("x")
// Remove "NOT(!)" from here your program will work as expected
if (choice.equalsIgnoreCase("x"))
{
//here you should assign loop to false if they continue
Loop = false;
answer = r.nextInt(range) + 1;
System.out.print("A new number");
break;
}
else if (choice.equalsIgnoreCase("y"))
{
//better to insert break here as well
//here you should assign loop to true if they wanna exit.
Loop = true;
System.out.print("END OF GAME");
exit = 11;
break;
}
}
else if (number > answer)
{
System.out.println("TOO HIGH");
}
else if (number < answer)
{
System.out.println("TOO LOW");
}
if (number == 0)
{
System.out.println("YOU GAVE UP. THE NUMBER WAS " + answer);
System.out.println("Enter x to continue to play or y to endgame");
// MADE CHANGES HERE
choice = input.next();
if (choice.equalsIgnoreCase("x"))
{
//here you should assign loop to false if they continue
Loop = false;
answer = r.nextInt(range) + 1;
System.out.print("A new number");
break;
}
else if (choice.equalsIgnoreCase("y"))
{
//better to insert break here as well
//here you should assign loop to true if they wanna exit.
Loop = true;
System.out.print("END OF GAME");
exit = 11;
break;
}
}
}
}
Please do copy-paste the code. Because it is working perfectly without any Exception..!!
My sample outputs:
SAMPLE 1:
Guess a number between 1 and 50 : 1
TOO LOW
Guess a number between 1 and 50 : 0
TOO LOW
YOU GAVE UP. THE NUMBER WAS 27
Enter x to continue to play or y to endgame
y
END OF GAME
SAMPLE 2:
Guess a number between 1 and 50 : 20
TOO HIGH
Guess a number between 1 and 50 : 19
TOO HIGH
Guess a number between 1 and 50 : 15
Your guess was correct
The number was: 15
You guess the number with: 3 guesses
Enter x to continue to play or y to endgame
x
A new numberGuess a number between 1 and 50 : 20
TOO LOW
Guess a number between 1 and 50 : 0
TOO LOW
YOU GAVE UP. THE NUMBER WAS 42
Enter x to continue to play or y to endgame
y
END OF GAME
Do let me know if there is any problem.
Well, if you wish to end a loop, you could use the break; command. It jumps out of a while or for loop. So you could use this if the number is 0:
if (number == 0)
{
System.out.println("YOU GAVE UP. THE NUMBER WAS " + answer);
System.out.println("Enter 'x' to continue to play or y to endgame");
choice = input.nextLine();
if(choice == "y")
{
break;
}
and add:
if(choice == "y") {break;} to the very end of the while(!Loop) loop.
And with the time when the answer is correct, you set Loop to false, which means !Loop would evaluate to true. You should change Loop = false to Loop = true when they decide to continue the game.
a small modification
public class HILOGAME {
public static void firstGame() {
final int range = 50;
int answer;
int number;
int guessNum = 0;
String choice = "";
Scanner input = new Scanner(System.in);
Random r = new Random();
answer = r.nextInt(range) + 1;
System.out.print("Guess a number between 1 and " + range + " : ");
number = input.nextInt();
if (number == answer) {
System.out.println(" Your guess was correct ");
System.out.println();
System.out.println("The number was: " + answer);
System.out.println("You guess the number with: " + guessNum + " guesses ");
System.out.println();
} else {
System.out.println("you entered a wrong value");
System.out.println("do you really want to try again? press y to continue or other alphabet to exit");
choice = input.next();
playAgain(choice);
}
}
public static void playAgain(String choice) {
if (choice.equalsIgnoreCase("Y")) {
firstGame();
} else {
System.out.println("you chose to quit");
System.exit(0);
}
}
I am writing a program that will ask the user to guess a random number 6 times. The program has to ask if they want to play again and will keep a running total of the wins/losses.
How would I have the program rerun?
heres the code:
import java.util.Scanner;
import java.util.Random;
public class Project {
public static void main(String[] args) {
String input;
double guess = 0;
int number;
double wins = 0;
double losses = 0;
String repeat;
Scanner keyboard = new Scanner(System.in);
Random randomNumbers = new Random();
System.out.println("Welcome to Higher/Lower!");
System.out.println("Enter your name: ");
input = keyboard.nextLine();
while(input.equalsIgnoreCase("yes")); {
number = randomNumbers.nextInt(100) + 1;
System.out.println("I've chosen my number, " + input + "You only have 6 tries, good luck!"); }
for(int num = 1; number != guess && number <= 6; num++) {
System.out.println("Enter guess " + num + ":");
guess = keyboard.nextDouble();
if(guess < number)
System.out.println("higher.");
else if(guess > number)
System.out.println("lower.");
else
System.out.println("Congratulations!"); }
if(guess == number) {
System.out.println("You guesses my number!"); wins++; }
if(guess != number) {
System.out.println("Sorry, " + input + " my number was " + number +
"You lose!"); losses++; }
System.out.println("Do you want to play again? (Yes/No): ");
repeat = keyboard.nextLine();
if(input.equalsIgnoreCase("no")); {
System.out.println("Thanks for playing!"); }
System.out.println(wins + " wins");
System.out.println(losses + " losses");
}
}
It is skipping over asking me if i want to play again or not and i dont know what kind of loop to use
Wihtout your code, I'm assuming this is what you need.
boolean doContinue = true;
do {
//guess random number 6 times
//do you want to continue?
// yes -> doContinue = true;
// no -> doContinue = false;
} while (doContinue );
I would suggest making your loop a do-while loop like this:
do {
for (int i=0; i<6; i++){
/*
insert code for the guessing/checking/etc.
*/
}
System.out.print("Would you like to continue? [Y/n] ");
} while (scan.next().toUpperCase().charAt(0) != 'Y');
so I am having trouble with being able to have a proper TOTAL guess counter.
My code needs to be basic so please dont offer me advice for doing anything you think is not trivial.
Currently,
my code plays a game, then asks the user if they want to play again and its a simple Y or N.
If yes, another games plays
If no then then game ends and it reports the results of every game played as such: the total games, guesses per game, and the best game (reports game that had lowest guess count).
My issues are being able to accurately count ALL THE GUESSES from every game. I am able to report results and track the total games played correctly but I can't figure out how to report a result that tracks the guesses per game, adds them all up, finds the smallest one.
import java.util.*;
public class GuessingGame {
public static final int MAX = 100;
public static void main(String[] args) {
Scanner console = new Scanner(System.in); //to use scanner
Random r = new Random(); //to use random numbers
intro();
int totalGuesses = guess(console, r);
System.out.print("Do you want to play again? ");
String answer = console.next();
int plays = 1;
//while loop reads user input and determines wether
//or not to play the game again
while(answer.charAt(0) == 'y' || answer.charAt(0) == 'Y') {
System.out.println();
guess(console, r);
System.out.print("Do you want to play again? ");
answer = console.next();
plays++;
}
System.out.println();
results(plays, totalGuesses);
}
}
//method that creates the guessing game and congratulatory message
public static int guess(Scanner console, Random r) {
System.out.println("I'm thinking of a number between one and " + MAX + "...");
int theNumber = 50; //creates a random answer between one and the MAX class constant
int userGuess = 0;//establishes the integer for the user's guess
int guesses = 0; //establishes the amount of guesses
int totalGuesses = 0;
while(userGuess != theNumber) { //while loop that executes until answer is correct
System.out.print("Your guess? ");
userGuess = console.nextInt();
if(userGuess > theNumber) {
System.out.println("It's lower.");
} else if (userGuess < theNumber) {
System.out.println("It's higher.");
}
guesses++;
}
if(guesses == 1) {
System.out.println("You got it right in 1 guess!");
} else {
System.out.println("You got it right in " + guesses + " guesses!");
}
totalGuesses += guesses;
return totalGuesses;
}
//prints out the stats of the game
public static void results(int plays, int totalGuesses) {
System.out.println("Overall results:");
System.out.println("Total games = " + plays);
System.out.println("Total guesses = " + totalGuesses);
System.out.println("Guesses/game = ");
System.out.println("Best game = ");
}
}
Your variable called "guesses" must be created in the main class, not inside the guess method.
Then, just add it to the method ( public static int guess (scanner,random,int guesses))
Your variables guesses and totalGuesses needs to be instantiated outside of the method. Put int guesses and int totalGuesses just above
public static int guess(Scanner console, Random r) {
System.out.println("I'm thinking of a number between one and " + MAX + "...");
so that it is like this
int guesses = 0;
int totalGuesses = 0;
public static int guess(Scanner console, Random r) {
System.out.println("I'm thinking of a number between one and " + MAX + "...");
and remove them from inside of the class so that its like this.
int userGuess = 0;//establishes the integer for the user's guess
while(userGuess != theNumber)
You should also add guesses = 0; in the main class here.
System.out.print("Do you want to play again? ");
answer = console.next();
plays++;
guesses = 0;
}
Here's the whole code in one main method. Maybe it'll shed some light.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
Random r = new Random();
int MAX = 100; //ceiling for the random number
int total = 0; //total number of guess
int plays = 0; //total number of games
int bestGame = Integer.MAX_VALUE; //used to determine game with lowest amount of guesses
String answer; //holds user input
boolean playing = true; //used to determine if the game is ongoing
while (playing) { //while game is ongoing
System.out.println("I'm thinking of a number between one and " + MAX + "...");
int theNumber = r.nextInt(MAX) + 1; //generate random int [1, 100]
int userGuess = 0; //holds user guess
int guesses = 0; //total number of guesses this game
while(userGuess != theNumber) { //while number is not guessed
System.out.print("Your guess?\n");
userGuess = console.nextInt();
if (userGuess > theNumber) System.out.println("It's lower.");
else if (userGuess < theNumber) System.out.println("It's higher.");
guesses++; //increase guesses this round by 1
}
if (guesses < bestGame) bestGame = guesses; //if we used less guesses than in our best game this is our new best game
System.out.println("You got it right in " + guesses + " guess(es)!");
plays++; //increase number of games by 1
total += guesses; //increase total guesses by guesses this round
System.out.println("Again?");
answer = console.next();
if (answer.toLowerCase().equals("n")) playing = false; //if input is n (or N) we exit the loop
}
console.close(); //close scanner
System.out.println("Overall results:"); //print results
System.out.println("Total games = " + plays);
System.out.println("Total guesses = " + total);
System.out.printf("Guesses/game = %.2f%n", (double) total/plays); //cast to double to prevent integer division
System.out.println("Best game = " + bestGame);
}
Im making a guessing game for my class and I need some help for adding a "play again" feature at the end of the game when you've guessed the right number:
public class GuessingGame
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Random rand = new Random();
int numtoguesses = rand.nextInt(1000) + 1;
int counter = 0;
int guess = -1;
while (guess != numtoguesses)
{
System.out.print ("|" + numtoguesses + "|" + "Guess the right number: ");
guess = input.nextInt();
counter = counter + 1;
if (guess == numtoguesses)
System.out.println ("YOU WIN MOFO!");
else if (guess < numtoguesses)
System.out.println ("You're to cold!");
else if (guess > numtoguesses)
System.out.println ("You're to hot!");
}
System.out.println ("It took you " + counter + " guess(es) to get it correct");
}
}
One simple approach would be to move the code you've written into a function
public void play() {
...
}
and from main do something like:
do {
play();
playAgain = promptUser;
} while(playAgain);
Just put another while loop over everything.
boolean playing = true;
while(playing) {
while(guess != numtoguesses) { // All code }
System.out.println("Do you wish to play again? Y/N");
String answer = input.nextLine();
playing = answer.equalsIgnoreCase("y");
count = 0;
guess = -1;
}
Everything together:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
int numtoguesses = rand.nextInt(1000) + 1;
int counter = 0;
int guess = -1;
boolean playing = true;
while(playing) {
while (guess != numtoguesses) {
System.out.print ("|" + numtoguesses + "|" + "Guess the right number: ");
guess = input.nextInt();
counter = counter + 1;
if (guess == numtoguesses)
System.out.println ("YOU WIN MOFO!");
else if (guess < numtoguesses)
System.out.println ("You're to cold!");
else if (guess > numtoguesses)
System.out.println ("You're to hot!");
}
}
System.out.println ("It took you " + counter + " guess(es) to get it correct");
System.out.println("Do you wish to play again? Y/N");
String answer = input.nextLine();
playing = answer.equalsIgnoreCase("y");
count = 0;
guess = -1;
numtoguesses = rand.nextInt(1000) + 1;
}
You should extract this in a few methods, but I'll leave that up to you.
There are a lot of options I can think about. The quickest:
-- place all the code between lines int numtoguesses = rand.nextInt(1000) + 1; (inclusive) and end of main method inside an infinite loop
-- at the end of your current code block, add an interogation to the user, asking him whether he/she wants to play again (you can define a convention for the pressed keys); this part is placed also inside the infinite loop
-- if he/she doesn't want to, break the (outer) infinite loop