Its my first year in college and i need to fix this program for my homework. How do i get the program to loop back for another input after the user has entered his/her first guess?
import javax.swing.JOptionPane;
import java.util.*;
public class Guessing {
public static void main(String[] args) {
final int MAX = 20;
int answer, guess, lowcount = 0, highcount = 0;
String sguess;
Random generator = new Random();
answer = generator.nextInt(MAX) + 1;
do {
sguess = JOptionPane.showInputDialog("I'm thinking of a number between 1 and " + MAX + ". Guess what it is: ");
guess = Integer.parseInt(sguess);
if (guess > answer) {
JOptionPane.showMessageDialog(null, "That is TOO HIGH!");
highcount++;
break;
} else if (guess < answer) {
JOptionPane.showMessageDialog(null, "That is TOO LOW!");
lowcount++;
break;
}
}
while (guess != answer);
}
}
You need to remove the break statements in your 'do-while' loop.
Related
Design an application that picks a random number 1 through 100, and then prompt the user to guess the number, warning the user they only have 5 tries remaining to guess correctly. After each guess, report to the user whether he or she is correct or guess was too high or too low. If guesses correctly, print out congratulatory message. If guess 5 times unsuccessfully, print a message saying the game is over. At the end of the game, prompt hte user to indicate whether or not he/she wishes to play again.
I specifically need help with the ending, and I guess also the layout of the code... I run it and it continually runs, I've tried using several websites and my textbook but no luck, thank you in advance!!
Java, Net beans 8.2
import java.util.Random;
import java.util.Scanner;
public class GuessingGame
{
public static void main (String[]args)
{
int answer, guess,attemptsNum = 0;
final int maxAttempts = 5;
String str, another = "y";
Scanner scan = new Scanner(System.in);
Random generator = new Random();
answer = generator.nextInt(101)+1;
System.out.println("Guess a number between 1 and 100");
System.out.println("Enter your guess (0 to quit):");
{
guess = scan.nextInt();
while (guess != 0)
{
if(guess==answer)
System.out.println("Right!");
else if (guess<answer)
System.out.println("Your guess was too LOW.");
else if (guess>answer)
System.out.println("Your guess was too HIGH.");
}
System.out.println("Want to Play again?(y/n)");
another = scan.next();
while (guess != answer && ++attemptsNum < maxAttempts)
if (attemptsNum == maxAttempts)
System.out.println ("The number was " + answer);
}
}
}
Enter your guess (0 to quit): 20
Your guess was too LOW
Enter your guess (0 to quit): 35
Your guess was too LOW
Enter your guess (0 to quit): 80
Your guess was too HIGH
Enter your guess (0 to quit): 74
Your guess was too HIGH
Enter your guess (0 to quit): 56
Right! Guesses:5
Play again (y/n)?
Couple of comments:
You need to work on your formatting of the code. This makes it a lot more readable.
Your generator generates a value between 1 and 101. It should just be answer = generator.nextInt(100)+1;
Your loops and some of your logic is wrong
I would suggest always creating a separate method outside public static void main. This is common practice, and this also allows you to call the method it self again.
This is how i would solve it:
import java.util.Random; import java.util.Scanner;
class Main {
public static Scanner scan = new Scanner(System.in);
public static void main (String[]args) {
runGame();
}
public static void runGame() {
String another = "";
int answer, guess,attemptsNum = 0;
final int maxAttempts = 5;
Random generator = new Random();
answer = generator.nextInt(100)+1;
System.out.println("Guess a number between 1 and 100");
System.out.println("Enter your guess (0 to quit):");
guess = scan.nextInt();
while (guess != answer && attemptsNum < maxAttempts-1 && guess != 0 ) {
if(guess==answer)
System.out.println("Right!");
else if (guess<answer) {
System.out.println("Your guess was too LOW.");
attemptsNum++;
guess = scan.nextInt();
}
else {
System.out.println("Your guess was too HIGH.");
attemptsNum++;
guess = scan.nextInt();
}
}
System.out.println ("The number was " + answer);
System.out.println("Want to Play again?(y/n)");
another = scan.next();
System.out.println("another = " + another);
if(another.equals("y")) {
runGame();
} else {
System.out.println("Goodbye!");
}
}
}
But either way, just continue to practice. You will get the hang of it!
I see the outer while loop needs to be restructured and some of the logic is misplaced. Try the revised version, hope this helps. Comment me if you have any questions.
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
int answer, guess, attemptsNum = 0;
final int maxAttempts = 5;
String str, another = "y";
Scanner scan = new Scanner(System.in);
Random generator = new Random();
answer = generator.nextInt(101) + 1;
while (another.equals("y") || another.equals("Y")) {
System.out.println("Guess a number between 1 and 100");
System.out.println("Enter your guess (0 to quit):");
guess = scan.nextInt();
attemptsNum = 0;
while (guess != 0)
{
attemptsNum++;
if (guess == answer) {
System.out.println("Right!");
break;
} else if (guess < answer)
System.out.println("Your guess was too LOW.");
else if (guess > answer)
System.out.println("Your guess was too HIGH.");
if (attemptsNum == maxAttempts) {
System.out.println("The number was " + answer);
break;
}
System.out.println("Enter your guess (0 to quit):");
guess = scan.nextInt();
}
System.out.println("Want to Play again?(y/n)");
another = scan.next();
}
System.out.println("Thanks for playing");
}
}
I can see that javapedia.net has answered first, but I have come up with this answer independently. I have added brackets for readability. attemptsNum++ is added to the if statements for a guess being too high or low.
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
int answer, guess, attemptsNum = 0;
final int maxAttempts = 5;
String str, another = "y";
Scanner scan = new Scanner(System.in);
Random generator = new Random();
answer = generator.nextInt(101) + 1;
System.out.println("Guess a number between 1 and 100");
System.out.println("Enter your guess (0 to quit):");
guess = scan.nextInt();
while (guess != 0) {
if (guess == answer) {
System.out.println("Right!");
guess = 0;
} else if (guess < answer) {
System.out.println("Your guess was too LOW.");
attemptsNum++;
guess = scan.nextInt();
} else {
System.out.println("Your guess was too HIGH.");
attemptsNum++;
guess = scan.nextInt();
}
if (attemptsNum >= (maxAttempts-1)) {
System.out.println("The number was " + answer);
}
}
}
}
Ok I need help on a school assignment that I'm currently stuck on and I need a lot of help. I have tried to do this for hours and still cant figure out on how to do this assignment. This is my code below.
I'm trying to create a guessing game. What I'm stuck on is how I'm suppose to loop the number of 10 guesses and no more. I tried it and it gives me an infinite loop.
What im trying to create:
A number from 1 and 100 is picked and the player does not know what the number is.
The player is asked to guess a number from 1 to 100.
They have 10 chances to guess the right number.
If the player does not guess the correct number within 10 guesses then the player loses the game.
You let them know if their guess is too low or too high to help them narrow down their guesses to eventually guess the right number before their 10 guesses are used up.
import java.util.Scanner;
import java.util.Random;
public class GuessGame3
{
public static void main (String[] args){
int num1;
int count=0;
int Guess=0;
Random generator = new Random();
Scanner scan = new Scanner(System.in);
//get generator
num1 = generator.nextInt(100) + 1;
while (Guess != num1){
System.out.println("Enter a number between 1 and 100");
Guess = scan.nextInt();
count++;
while (count > 10)
System.out.println("Sorry you didnt guess in 10 trues its been " + count + " tries");
if ( Guess > num1)
{
System.out.println("Lower!");
}
else if (Guess < num1)
{
System.out.println("Higher");
}
else
System.out.println("Congratz with " + count + " amount of tries");
}
}
}
I recommend putting the checks if the guess is as part of the first while loop, not a nested one.:
while (count < 10){
System.out.println("Enter a number between 1 and 100");
Guess = scan.nextInt();
count++;
if ( Guess > num1)
{
System.out.println("Lower!");
}
else if (Guess < num1)
{
System.out.println("Higher");
}
else {
break;
}
}
if(count < 10) {
System.out.println("Congrats! You have completed it in " + count + " tries!");
} else {
System.out.println("Sorry you have run out of your 10 guesses!");
}
There might be some errors here, but you should get the gist.
Problem lies with the loop and in the order you have validated the total number of tries and the Guess match. Try the below
import java.util.Scanner;
import java.util.Random;
public class TestGame
{
public static void main(String[] args)
{
int num1;
int count = 0;
int Guess = 0;
int maxAllowedRetries = 10;
Random generator = new Random();
Scanner scan = new Scanner(System.in);
//get generator
num1 = generator.nextInt(100) + 1;
while(count <= maxAllowedRetries)
{
if(count == maxAllowedRetries)
{
System.out.println("Sorry you have reached maximum number of retries!");
break;
}
count++;
System.out.println("Enter a number between 1 and 100");
Guess = scan.nextInt();
if(Guess == num1)
{
System.out.println("Great you got it Right!");
break;
}
System.out.println("Sorry you didnt guess right. Its been " + count + " tries");
if(Guess > num1)
{
System.out.println("Lower!");
}
else if(Guess < num1)
{
System.out.println("Higher");
}
}
}
}
the application is a simple guessing game which i got that part down. my issue is making a method that before any guessing starts the player must first guess the right amount of digits in a number
e.g the guess being 314 and the answers has 3 digits in it then the guessing of too high two low starts otherwise it keeps looping until you guess the right amount of digits.
now i have created the method to do this my issue is a rather simple one i think but its a matter of initializing the variables and that's where i am having problems.
import java.util.Random;
import java.util.Scanner;
public class NumberGuess
{
public static void main (String[] args)
{
final int MAX = 1000;
int answer, guess;
Scanner Keyboard = new Scanner(System.in);
Random generator = new Random(); //Random generator. 1 to 100.
answer = generator.nextInt(MAX) +1;
guess = Keyboard.nextInt();
System.out.print ("I'm thinking of a number between 1 and "+ MAX + ". Guess what it is: (or enter 0 to quit) ");
do
{
System.out.print("Guess what the number is: ");
guess = Keyboard.nextInt();
if (guess > answer && guess != 0)
System.out.println("Your guess is too high!");
else if (guess < answer && guess !=0)
System.out.println("Your guess is too low!");
if(guess==0)
System.out.println("you have ended your game");
else if (guess == answer)
System.out.println("You got it!");
} while (guess != answer&& guess!=0);
}
int NumOfDigits(int number)
{
int numDigits = 0;
while (number/10 > 0);
{
number = number/10;
numDigits++;
}
return numDigits;
}
int guess;
Scanner Keyboard1 = new Scanner(System.in);
guess = Keyboard1.nextInt();
int target = NumOfDigits(answer);
while(NumOfDigits(guess) != target);
{
System.out.println("read anothrer input guess");
guess = Keyboard1.nextInt();
}
System.out.println("you got the correct number of digits now guess the number!");
guess = Keyboard1.nextInt();
}
your method for counting diigits is wrong it should be like this
public static int NumOfDigits(int number)
{
int numofdigits = 0;
while(number>0){
numofdigits++;
number = number/10;
}
return numofdigits;
}
because your method returns 2 and it should return 3
So I've been working on this and it works fine, only problem is that after you guess a number that's not between 1 and 100, it goes onto the next guess when the try shouldn't count against you. I've attached a picture of what the output SHOULD look like.
Do I need a 'for' statement or a boolean variable?
And here is my code:
Random generator = new Random();
//import the scanner for prompt
Scanner input = new Scanner(System.in);
//integers for the secret number, input guess of the secret number, tries and limit to tries
int numberToGuess = 1 + generator.nextInt(100);
int numberOfTries = 1;
int limit = 10;
int guess;
//prompt user to enter a number to guess
System.out.println("You have 10 tries to guess a number between 1 and 100");
//start of while loop
while (numberOfTries <= 10) {
System.out.print("Guess number " + numberOfTries + ": ");
guess = input.nextInt();
//if else statements (outputs)
if (guess < numberToGuess)
System.out.println("Your guess is too low. Try again.");
else if (guess > 100)
System.out.println("Guesses should be between 1 and 100.");
else if (guess > numberToGuess)
System.out.println("Too high. Try again.");
else if (guess == numberToGuess) {
System.out.println("Congratulations! You have correctly guess the number in " + numberOfTries + " tries");
System.exit(0);
} else {
System.out.println("Sorry, you did not guess the guess the answer in 10 tries");
System.out.println("The number was " + numberToGuess);
//break to end while loop
break;
}
numberOfTries++;
// If statement after executing the while loop the output if user loses and answer to secret number
if (numberOfTries > 10) {
System.out.println("Sorry, you did not guess the guess the answer in 10 tries");
System.out.println("The number was " + numberToGuess);
}
}
Don't increment numberOfTries++; if they guess a number outside of the range. Put the increment inside the if statements
Try using a nested do-while loop inside your primary while loop:
//start of while loop
while(numberOfTries <= 10){
//get a valid guess
do{
boolean valid = true;
System.out.print("Guess number " + numberOfTries + ": ");
guess= input.nextInt();
//if else statements (outputs)
if (guess < numberToGuess){
System.out.println("Your guess is too low. Try again.");
valid = false;
}
else if (guess > 100){
System.out.println("Guesses should be between 1 and 100.");
valid = false;
}
while (!valid);
//handle the valid guess
}
Here's how I'd do it. You tell me which one you prefer:
import java.util.Random;
import java.util.Scanner;
/**
* Created by Michael
* Creation date 3/4/2016.
* #link https://stackoverflow.com/questions/35809392/while-loop-in-java-number-guess
*/
public class NumberGuess {
public static final int MIN_VALUE = 1;
public static final int MAX_VALUE = 100;
public static final int MAX_TRIES = 10;
public static void main(String[] args) {
Random generator = new Random();
Scanner input = new Scanner(System.in);
String playAgain;
do {
int answer = MIN_VALUE + generator.nextInt(MAX_VALUE);
System.out.println(String.format("You have %d tries to guess a number between %d and %d", MAX_TRIES, MIN_VALUE, MAX_VALUE));
boolean correct = playGuessingGame(input, answer);
if (!correct) {
System.out.println(String.format("The number was %d", answer));
}
System.out.print("Play again? [Y/N]: ");
playAgain = input.nextLine();
} while ("Y".equalsIgnoreCase(playAgain));
}
public static boolean playGuessingGame(Scanner input, int answer) {
boolean correct = false;
int numTries = 0;
do {
System.out.print(String.format("Guess %d: ", ++numTries));
int guess = Integer.parseInt(input.nextLine());
if (guess < MIN_VALUE) {
System.out.println(String.format("Guess %d is below minimum %d", guess, MIN_VALUE));
} else if (guess > MAX_VALUE) {
System.out.println(String.format("Guess %d is above maximum %d", guess, MAX_VALUE));
} else if (guess < answer) {
System.out.println(String.format("Guess %d is too low. Try again.", guess));
} else if (guess > answer) {
System.out.println(String.format("Guess %d is too high. Try again.", guess));
} else {
System.out.println("Woo hoo! You got it right!");
correct = true;
break;
}
} while (numTries < MAX_TRIES);
return correct;
}
}
You and your professor realize that it's almost impossible to lose this game. Right?
A bisection strategy says you can always get the right answer with 10 tries. Make that number smaller for a challenge.
increamenting should be done inside the if statemnt :D
First of all, I'd like to say that I am REALLY new to all of this... I've tried learning as much as I can, so apologies if any of my code seems ridiculous or all-over-the-place, but I needed somewhere to start. (By the way, credit to the very base of this code goes to CrossCoastGaming: http://tinyurl.com/kktyq4e).
Now to the matter at hand. I have improved (for lack of a better word) on the coding that the man in the video shows, by adding several different phrases, making use of variables and adding a try counter. Here is my code:
import java.util.Random;
import java.util.Scanner;
public class Main {
public static int number, guess, tryCount, replay;
public static int maxValue =1;
public static Scanner scan;
public static Random rand;
public static void main(String args[]) {
scan = new Scanner(System.in);
rand = new Random();
System.out.print("Enter a maximum number: ");
while(maxValue < 2)
maxValue = scan.nextInt();
number = rand.nextInt(maxValue);
System.out.print("Guess a number from 1 to " + maxValue + ": ");
while (guess != number) {
guess = scan.nextInt();
tryCount++;
if (guess < 1) {
System.out.print("Guess is not positive. Try again: ");
}else if (guess < number) {
System.out.print("Too low! Try again: ");
}
if (guess > maxValue) {
System.out.println("Guess is higher than " + maxValue + ". Try again: ");
}else if (guess > number) {
System.out.print("Too high! Try again: ");
}
}
if (tryCount == 1) {
System.out.println("Nailed it! It only took you 1 try!");
}
else {
System.out.println("Nailed it! It took you " + tryCount + " tries.");
}
System.out.println("Type 0 to play again. Type 1 to quit.");
if (replay == 1) {
replay = scan.nextInt();
}
}
}
Ok, so hopefully that gives anyone who knows what they're doing an idea of my goal. Now, as you can see by this line:
if (replay == 1) {
replay = scan.nextInt();
}
I would like to write a way so people can replay the game without having to reboot the file. I already have an idea of what I kind of would like to do, but I've searched everywhere and can't seem to find out what to continue with after this point. I'm sure that I'm missing something. Any help would be greatly appreciated.
You can use a do-while loop to achieve this:
import java.util.Random;
import java.util.Scanner;
public class Main {
public static int number, guess, tryCount, replay;
public static int maxValue = 1;
public static Scanner scan;
public static Random rand;
public static void main(String args[]) {
scan = new Scanner(System.in);
rand = new Random();
do { // start of do-while loop
tryCount = 0; // reset tryCount
System.out.print("Enter a maximum number: ");
while(maxValue < 2) {
maxValue = scan.nextInt();
}
number = rand.nextInt(maxValue);
System.out.print("Guess a number from 1 to " + maxValue + ": ");
while (guess != number) {
guess = scan.nextInt();
tryCount++;
if (guess < 1) {
System.out.print("Guess is not positive. Try again: ");
} else if (guess < number) {
System.out.print("Too low! Try again: ");
}
if (guess > maxValue) {
System.out.println("Guess is higher than " + maxValue + ". Try again: ");
} else if (guess > number) {
System.out.print("Too high! Try again: ");
}
}
if (tryCount == 1) {
System.out.println("Nailed it! It only took you 1 try!");
} else {
System.out.println("Nailed it! It took you " + tryCount + " tries.");
}
do { // check the user's input
System.out.println("Type 0 to play again. Type 1 to quit.");
replay = scan.nextInt();
if (replay != 0 && replay != 1) {
System.out.println("Input not recognized.");
}
} while (replay != 0 && replay != 1);
} while (replay == 0); // end of do-while loop
}
}
do-while loops are always executed at least once. The condition is checked at the end of the loop.