How to add the "play again?" feature for java - java

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

Related

Problem with keeping score with a while loop (Java)

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("--------------------------------------------");
}
}
}

Java loop for game

I'm having trouble with my code. For some reason, each time I run the code the " if (guess <1 || guess >10 )
System.out.println ("Your guess needs to be between 1 and 10");" statement is counted as a guessing attempt. The goal is to not have the attempt count if the player is guessing out of the 1-10 range. I've tried a break;, but I can't get it right? Does anyone know how to break the loop and return to the guessing, if a user is out of range(without it counting as an attempt)?
Thank you
import java.security.SecureRandom;
import java.util.Scanner;
public class GuessTheNumber {
private Scanner input = new Scanner(System.in);
private SecureRandom randomNumbers = new SecureRandom();
private int numberOfGuesses;
public void play() {
numberOfGuesses = 0;
int magicNumber = 1 + randomNumbers.nextInt(10);
int guess = askForGuess();
while(guess != magicNumber){
// Some kind of loop, maybe while
numberOfGuesses++;
// is theGuess equal to magicNumber or is it
guess = input.nextInt();
// too high or is it too low
if (guess == magicNumber)
System.out.println("Yes, the number is " + magicNumber);
else if (guess > magicNumber)
System.out.println("Your guess is too high");
else if (guess < magicNumber)
System.out.println("Your guess is too low");
System.out.println ("Number of times guessed: "
+ numberOfGuesses );
// Display "correct in numberOfGuesses"
}
}
}
private int askForGuess( ) {
int guess = 0;
// prompt for a guess
System.out.println("Enter a number:");
if (guess <1 || guess >10 )
System.out.println ("Your guess needs to be between 1 and 10");
return guess;
}
}
You need to take input in the method "askForGuess()" also the increment will be done there too some thing like following
public class GuessTheNumber
{
private Scanner input = new Scanner(System.in);
private SecureRandom randomNumbers = new SecureRandom();
private int numberOfGuesses;
public void play() {
numberOfGuesses = 0;
int magicNumber = 1 + randomNumbers.nextInt(10);
int guess = 0;
while(guess != magicNumber){
// Some kind of loop, maybe while
guess = askForGuess();
// is theGuess equal to magicNumber or is it
if (guess == magicNumber)
System.out.println("Yes, the number is " + magicNumber);
else if (guess > magicNumber)
System.out.println("Your guess is too high");
else if (guess < magicNumber)
System.out.println("Your guess is too low");
System.out.println ("Number of times guessed: " + numberOfGuesses );
}
}
private int askForGuess( )
{
int guess = 0;
// prompt for a guess
System.out.println("Enter a number:");
guess = input.nextInt();
if (guess <1 || guess >10 )
System.out.println ("Your guess needs to be between 1 and 10");
else
numberOfGuesses++;
return guess;
}
}

Having trouble w/ returning and passing values; "counting"

Our task was to create a guessing game, where the computer would generate a number and the user was prompted to guess. We were to create a method to play only one game, and then create a while loop in the main to make the game playable again. In the end, we need to show statistics. I'm having trouble with showing the "best game." That is a game where the amount of guesses is the least.
Here is the code:
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static final int MAX = 100;
// This is the main. Here we can see a do/while loop
// and a few variables that were created to compliment it.
public static void main(String[] args) {
Random rand = new Random();
Scanner console = new Scanner(System.in);
intro();
String s = "";
int totalGames = 0;
int totalGuess = 0;
do {
totalGuess = game(console);
System.out.print("Do you want to play again? ");
s = console.next();
totalGames++;
} while (s.equals("y") || s.equals("Y") || s.equals("Yes") ||
s.equals("yes") || s.equals("Yes"));
totalGuess = totalGuess;
statistics(totalGames, totalGuess);
}
// This method prints out the intro.
public static void intro() {
System.out.println("This program allows you to play a guessing
game.");
System.out.println("I will think of a number between 1 and");
System.out.println(MAX + " and will allow you to guess until");
System.out.println("you get it. For each guess, I will tell you");
System.out.println("whether the right answer is higher or lower");
System.out.println("than your guess.\n ");
}
// This method plays the game only once. It's later used in the main.
// Returns the
// number of guesses for one game.
public static int game(Scanner console) {
Random rand = new Random();
int random = rand.nextInt(MAX) + 1;
System.out.println("I'm thinking of a number between 1 and " + MAX + "
... (it's " + random + " )");
System.out.print("Your guess? > ");
int guess = console.nextInt();
int count = 0;
do {
if ((random - guess) > 0) {
System.out.println("It's higher.");
System.out.print("Your guess? > ");
guess = console.nextInt();
count++;
}
else if ((random - guess) < 0) {
System.out.println("It's lower.");
System.out.print("Your guess? > ");
guess = console.nextInt();
count++;
}
else if (random == guess) {
count++;
}
} while (random != guess);
if (count == 1) {
System.out.println("You got it right on the first guess!!");
}
else {
System.out.println("You got it right in " + count + " guesses.");
}
return count;
}
// This method prints out the statistics.
public static void statistics(int x, int y) {
System.out.println("total games = " + x);
System.out.println("total guesses = " + (y));
System.out.println("guesses/game = ");
System.out.println("best game = ");
}
}
Have a look when totalGuess is assigned:
public static void main(String[] args) {
Random rand = new Random();
Scanner console = new Scanner(System.in);
intro();
String s = "";
int totalGames = 0;
int totalGuess = 0;
// ^ Initialized to zero
do {
totalGuess = game(console);
// ^ Assigned (not added) to the return value from game.
// Did you mean: totalGuess += game(console); ?
System.out.print("Do you want to play again? ");
s = console.next();
totalGames++;
} while (s.equals("y") || s.equals("Y") || s.equals("Yes") ||
s.equals("yes") || s.equals("Yes"));
totalGuess = totalGuess;
// ^ Assigned to itself. No action.
statistics(totalGames, totalGuess);
}

Having issues with having a program re-run

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');

Creating 1 decimal place

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

Categories

Resources