Ask the user to guess a number until the guess is equal random number. press 0 to quit and ask the user if they want to play again.
My problem, 0 for quit is, not working. How can I make it work with while loop?
thanks
import java.util.Random;
import java.util.Scanner;
public class Guessing
{
public static void main(String[]args){
String playAgain = "y";
final int MAX =100;
int randomNumber;
int numberofGuess = 0;
int guess ;
boolean flag=false;
Scanner input = new Scanner(System.in);
Random rand = new Random();
Scanner inputYes= new Scanner(System.in);
while(playAgain.equalsIgnoreCase("y"))//do
{
System.out.println("Guess a number between 1 and "+ MAX );
randomNumber = rand.nextInt(MAX) +1;
numberofGuess = 0;
System.out.println( "enter a guess(0 to quit):");
guess= input.nextInt();
numberofGuess++;
if(guess >0)
if (guess == randomNumber)
{
System.out.println("you guessed corect.");
System.out.println("you guessed " +numberofGuess+ " times");
}
else if(guess < randomNumber)
System.out.println("you guess is too low.");
else if(guess > randomNumber)
System.out.println("you guess is too high.");
System.out.println("Do you want to play again? (y/n)");
playAgain = inputYes.nextLine();
}//while(playAgain.equalsIgnoreCase("y"));
}
}
Your loop runs until the expression in parantheses is false:
while (true) {
// this will be executed forever
}
while (false) {
// this will never be executed
}
a = 0;
while (a == 0) {
a = 1;
// this will be executed exactly once, because a is not equal 0 on the second run
}
guess = 1
while (guess != 0) {
// this will executed until the user enters "0"
readln(guess);
}
Please keep in mind that this is pseudo code. It will not compile.
Related
import java.util.Random;
import java.util.Scanner;
public class Activity3 {
public static void main(String[] args) {
//Variables
Scanner input = new Scanner(System.in);
Random Machine = new Random();
int num = Machine.nextInt(10);
do {
System.out.println("Guess the random generated number of the machine from 1-10");
int guess = input.nextInt();
if (guess == num) {
System.out.println("Correct number= " + num);
System.out.println("You Win!");
} else if (guess <= 0 && guess >= 11) {
System.out.println("Invalid Number!");
}
if (guess > 1 && guess < 10){
System.out.println("You Lose:<");
}
System.out.println("Do you want to try again?");
} while (input.next().equalsIgnoreCase("YES"));
input.close();
}
}
If I guess the correct number it outputs " you win!".
If I guess wrong it outputs "you lose". But If I guess a number that isn't in 1-10 it doesn't output the "Invalid Number" and just proceeds to output the "Do you want to try again?".
Random#nextInt(int) will return a value from 0 to bound - 1, so it's possible that the guess could be 0 in your code. You'd correct this by adding 1 to the guess, for example int num = Machine.nextInt(10) + 1;
Look at your logic...
else if(guess <= 0 && guess >= 11) {
if guess <= 0 AND guess >= 11 ... well, that's impossible.
I would change your logic flow, focusing on "happy paths" first.
That is, is the input within the acceptable range? If so, is guess == num if so, you win, otherwise print error messages.
For example...
Scanner input = new Scanner(System.in);
Random Machine = new Random();
int num = Machine.nextInt(10) + 1;
boolean done = false;
do {
System.out.println("Guess the random generated number of the machine from 1-10");
// Read the WHOLE line of text, removing the new line from the
// buffer which would otherwise be left by Scanner#nextInt
// and would cause no end of issues
String text = input.nextLine();
try {
// Try and parse the text to an int
int guess = Integer.parseInt(text);
if (guess >= 1 && guess <= 10) {
if (guess == num) {
System.out.println("Correct number= " + num);
System.out.println("You Win!");
num = Machine.nextInt(10) + 1;
System.out.println("Would you like to play another game? (Yes/No)");
} else {
System.out.println("Incorrect, guess again");
System.out.println("Do you want to try again? (Yes/No)");
}
// Prompt the user to try again or play another game
text = input.nextLine();
done = !"yes".equals(text.toLowerCase());
} else {
System.out.println("Out of range");
}
} catch (NumberFormatException exp) {
System.out.println("Not a valid number");
}
} while (!done);
import java.util.Scanner;
import java.util.Random;
/*
* 1) the user can attempt many times and you need to display the number of successful attempt
* 2) the range of random number 1..49
* 3) output >> You successfully guess the number in 16 attempts
* 4) output >> Do you want to play again?
* */
public class GuessingGame {
public static void main(String[] args) {
Scanner uInput = new Scanner(System.in);
Random randNum = new Random();
int guessNumber, number, count=0;
String in;
char again;
System.out.println("Welcome to Guessing Game");
do {
number = randNum.nextInt(50); // random number in the range of 1..50
for(int i=0; i<5; i++)
{
System.out.println("Enter a number to guess: ");
guessNumber = uInput.nextInt(); // get guess number from user
if(guessNumber > number)
{
System.out.println("Too big");
}else if(guessNumber < number)
{
System.out.println("Too small");
}else
{
System.out.println("Success");
count+=1;
return;
}
}
System.out.println("You successfully guess the number in "+count);
System.out.println("Do you want to play again? ");
in = uInput.nextLine();
again = in.charAt(0); //again will hold the first character from in var
}while(again =='Y'|| again =='y');
System.out.println("Guessing game terminate, thank you");
}
}
public static void main(String[] args) {
System.out.println("Welcome to Guessing Game");
guessNumber();
System.out.println("Guessing game terminate, thank you");
}
private static void guessNumber() {
Scanner uInput = new Scanner(System.in);
Random randNum = new Random();
int guessNumber, number, count = 0;
String in;
char again;
boolean isCorrect = false;
number = randNum.nextInt(50); // random number in the range of 1..50
while (!isCorrect) {
System.out.println("Enter a number to guess: ");
guessNumber = uInput.nextInt(); // get guess number from user
count += 1;
if (guessNumber > number) {
System.out.println("Too big");
} else if (guessNumber < number) {
System.out.println("Too small");
} else {
System.out.println("Success");
isCorrect = true;
}
}
System.out.println("You successfully guess the number in " + count + " attempts");
System.out.println("Do you want to play again? yes/no");
in = uInput.next();
again = in.charAt(0); //again will hold the first character from in var
if (again == 'Y' || again == 'y') {
guessNumber();
}
}
All you have to do is to replace your do while loop with a while loop. But the point is that you must set an initial value 'Y' to your again char to start the while loop. the condition of the loop will be just the same. The code will be like : char again = 'Y';
while (again == 'Y' || again == 'y') {
System.out.println("Welcome to Guessing Game");
number = randNum.nextInt(50);
for (int i = 0; i < 5; i++) {
System.out.println("Enter a number to guess: ");
guessNumber = uInput.nextInt();
if (guessNumber > number) {
System.out.println("Too big");
} else if (guessNumber < number) {
System.out.println("Too small");
} else {
System.out.println("Success");
count += 1;
break;
}
}
System.out.println("You have successfully guessed the number for " + count + " times");
System.out.println("Do you want to play again? ");
in = uInput.next();
again = in.charAt(0); //again will hold the first character from in var
}
System.out.println("Guessing game terminate, thank you");
I must note that your count variable, contains the number of games which user has guessed the number successfully, and not the number of attempts during a single game. If you want to handle this too, create attempts variable inside the while loop and increase it whenever the user attempts.
Also I changed the line in = uInput.nextLine(); to in = uInput.next(); because I believe your scanner input will be skipped.
This is a Hi-Lo number guessing game code, and the program ends either when the user gets the correct number or enters -1 while playing the game.
Here, I was wondering if it is possible to make the program run again even after the user enters -1 and the game ends, for example, in a situation where the user feels like restarting the game without finishing the first game.
import java.util.Random;
import java.util.Scanner;
public class HighLowGame {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
Random generator = new Random();
int number =generator.nextInt(100) + 1;
int count = 0;
boolean game = true;
System.out.println("Please guess the number.(Enter -1 to quit): ");
while(game){
int guess = scanner.nextInt();
**//if user enters -1, the game ends
if(guess == -1){
break;
}**
//guessed number is out of range
if(guess>100 || guess<0){
System.out.println("The number should be between 0 and 100.");
}
//guessed number is smaller than the random number
if(guess < number && 0 <= guess && guess <= 100 ){
count++;
System.out.println("That is too low. Please try again.(Enter -1 to quit):");
}
// guessed number is bigger than the random number
else if(guess > number && 0 <= guess && guess <= 100){
count++;
System.out.println("That is too high. Please try again.(Enter -1 to quit):");
}
//guessed number is the same as the random number
else if(guess==number) {
count++;
System.out.println("Congratulations! You got the correct number.");
System.out.println("Your attempt was " + count + " tries.");
count = 0;
System.out.println("Would you like to play the game again?(yes/no): ");
String another = scanner.next();
if (another.equalsIgnoreCase("no")) {
break;
}
// if the user wants to play the game one more time, it starts again
else {
number = generator.nextInt(100) + 1;
System.out.println("Please guess the number(Enter -1 to quit): ");
}
}
}
}
}
You can just put the game into a method, and when the method ends, you just ask them.
Main:
public static void main(String[] args){
boolean flag = true;
while(flag){
play();//play the game
Scanner input = new Scanner(System.in);//read the respound
System.out.println("want to play again?");
if(input.nextLine().equal("no"){//Want to play? BTW: I'm assuming you only enter "no" or "yes"
flag = false;//Don't want to play
}
}
}
And the method:
public static void play(){
//create scanner, variables and a random number
Scanner scanner = new Scanner (System.in);
Random generator = new Random();
int number =generator.nextInt(100) + 1;
int count = 0;
boolean game = true;
//prompt user to enter a number
System.out.println("Please guess the number.(Enter -1 to quit): ");
while(game){
//user enters a number
int guess = scanner.nextInt();
//if user enters -1, the game ends
if(guess == -1){
break;
}
//guessed number is out of range
if(guess>100 || guess<0){
System.out.println("The number should be between 0 and 100.");
}
//guessed number is smaller than the random number
if(guess < number && 0 <= guess && guess <= 100 ){
count++;
System.out.println("That is too low. Please try again.(Enter -1 to quit):");
}
// guessed number is bigger than the random number
else if(guess > number && 0 <= guess && guess <= 100){
count++;
System.out.println("That is too high. Please try again.(Enter -1 to quit):");
}
//guessed number is the same as the random number
else if(guess==number) {
count++;
//displays the message and the attempt count
System.out.println("Congratulations! You got the correct number.");
System.out.println("Your attempt was " + count + " tries.");
}
}
}
BTW: you said when the user enters -1, you end the game, then why in the world do you want to ask the user again ?_?
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);
}
}
}
}
I am writing a simple java guessing game, the game is supposed to randomly pick a number between 1 and 100 and then after you pick the correct number it asks you if you would like to play again. I know i should be able to use a Do while loop to ask if the user would like to play again, but every time I try I cannot make it work. This is my fully functional program without the do while loop. If someone could help me prompt the user if they would like to play again I would be very thankful. I am still very new to programming.
Also I apologize if the indenting isn't 100% correct.
import java.util.Scanner;
import java.util.Random;
public class GuessingGame
{
public static void main (String [] args)
{
//Variables
Random randomNumber = new Random();
Scanner kbd = new Scanner(System.in);
int computerValue = randomNumber.nextInt(100);
int numberOfTries = 0;
int success = 0;
int guess = 0;
//Logic and While Loop
while (success ==0)
{
System.out.println("please enter an integer betwen 1 and 100 inclusive: ");
guess = kbd.nextInt();
numberOfTries++;
if (guess < 1 || guess > 100){
System.out.println("Invalid input");
}
else if (guess == computerValue){
success++;
System.out.println("Congratulations you won! Your numbers of tries was: " + numberOfTries + " and the number was: " + computerValue);
}
else if (guess < computerValue){
System.out.println("Your guess is too low!");
}
else if (guess > computerValue){
System.out.println("Your guess is too high!");
}
}
}
}
Try this:
while(true) {
computerValue = randomNumber.nextInt(100);
numberOfTries = 0;
while (true) {
System.out.println("please enter an integer betwen 1 and 100 inclusive: ");
guess = kbd.nextInt();
numberOfTries++;
if (guess < 1 || guess > 100) System.out.println("Invalid input");
else if (guess == computerValue) {
System.out.println("Congratulations you won! Your numbers of tries was: " + numberOfTries + " and the number was: " + computerValue);
// leave the first loop
break;
}
else if (guess < computerValue) System.out.println("Your guess is too low!");
else if (guess > computerValue) System.out.println("Your guess is too high!");
}
System.out.println("Do you want to play again? (1:Yes/2:No)");
// if input is not yes leave second loop
if(kbd.nextInt() != 1) break;
}
If you want to use a do while loop this would work.
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
public static void main(String[] args) {
//Variables
Random randomNumber = new Random();
Scanner kbd = new Scanner(System.in);
int computerValue;
int numberOfTries = 0;
int success = 0;
int guess;
boolean playAgain;
//Logic and While Loop
do {
computerValue = randomNumber.nextInt(100);
guess = 0;
playAgain = false;
while (guess != computerValue) {
System.out.println("Please enter an integer betwen 1 and 100 inclusive: ");
guess = kbd.nextInt();
numberOfTries++;
if (guess < 1 || guess > 100) {
System.out.println("Invalid input");
} else if (guess < computerValue) {
System.out.println("Your guess is too low!");
} else if (guess > computerValue) {
System.out.println("Your guess is too high!");
}
}
success++;
System.out.println("Congratulations you won! Your numbers of tries was: " + numberOfTries + " and the number was: " + computerValue);
System.out.println("Would you like to play again?");
switch (kbd.next()) {
case "yes":
playAgain = true;
break;
default:
break;
}
} while (playAgain);
System.out.println("Goodbye");
}
}
Prompt the user if he wants to play again at
else if (guess == computerValue) {
success++;
System.out.println("Congratulations you won! Your numbers of tries was: " + numberOfTries + " and the number was: " + computerValue);
}
If the user inputs yes success--;