I'm trying to make a number guessing game between the range from 1 to 100. The program will stop if the user guesses the correct number.
My current code:
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
public static void main(String[] args) {
Random randomNumber = new Random();
Scanner reader = new Scanner(System.in);
System.out.println("What's your guess? ");
int n = reader.nextInt();
reader.close();
int Number = randomNumber.nextInt(100 + 1);
int guess = n;
while (guess != Number) {
System.out.println("What's your guess? ");
new Scanner(System.in);
}
if (guess == Number) {
System.out.println("Your have guessed the correct number! ");
}
else if (guess < Number) {
System.out.println("Your number is too low! ");
}
else if (guess > Number) {
System.out.println("Your number is too high! ");
}
}
}
This is where using the formatter in your IDE is helpful. You would be able to see that the if conditions which are after the loop should be inside the loop and you should be reading the reading the guess from input.
BTW You should never close the input unless you explicitly don't want to read anything from it ever again.
try
Random randomNumber = new Random();
Scanner reader = new Scanner(System.in);
int number = randomNumber.nextInt(100 + 1);
while(true) {
System.out.println("What's your guess? ");
int guess = reader.nextInt();
if (guess == Number) {
System.out.println("You have guessed the correct number! ");
break; // no need to guess more
} else if (guess < Number) {
System.out.println("Your number is too low! ");
} else if (guess > Number) {
System.out.println("Your number is too high! ");
}
}
Change your while loop to
while (guess != Number) {
if (guess == Number) {
System.out.println("Your have guessed the correct number! ");
break;
}
else if (guess < Number) {
System.out.println("Your number is too low! ");
}
else if (guess > Number) {
System.out.println("Your number is too high! ");
}
System.out.println("Guess Again?");
guess = reader.nextInt();
}
The while loop is infinite loop. Also, you should avoid using 'Number' as variable name as there is a class in java with the same name java.lang.Number. You can also need any number of variables using single object of Scanner class. So, a cleaner code would look like this :
while (guess != number) {
System.out.println("What's your guess? ");
guess = reader.nextInt();
}
Now, if you solve above problems, your code will never go to the two else-if blocks, because by the time your while loop breaks you will have 'guess' always be equal to 'number'. I think what you are trying to achieve here is :
while (guess != number) {
System.out.println("What's your guess? ");
guess = reader.nextInt();
if (guess == number) {
System.out.println("Your have guessed the correct number! ");
}
else if (guess < number) {
System.out.println("Your number is too low! ");
}
else if (guess > number) {
System.out.println("Your number is too high! ");
}
}
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);
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 attempting to make a High Low number guessing game that reports to the user if their guess is too high, too low or accurate. Everything is working as expected with the exception of a successful guess (of all things). Upon entry of the correct number, the loop prints the "Your guess was correct" statement along with the number of tries.This is what I want. However, instead of asking if the user would like to replay next, it is returning the "too high" response. Have I nested this incorrectly?
import java.util.Scanner;
import java.util.Random;
public class hilo2 {
public static void main(String[] args) {
int guess = 0;
int attempts;
String quit;
boolean replay = true;
Scanner scan = new Scanner(System.in);
Random generator = new Random();
while (replay) {
attempts = 0;
int answer = generator.nextInt(101) + 1;
System.out.println(answer);//for testing
System.out.println("Guess a number between 1 and 100. Enter your guess (0 to quit): ");
guess = scan.nextInt();
scan.nextLine();
while (guess != 0){
if (guess < answer) {
System.out.println("You guess was too low. Guess again (0 to quit): ");
guess = scan.nextInt();
scan.nextLine();
attempts++;
}
else if (guess > answer) {
System.out.println("Your guess was too high. Guess again (0 to quit): ");
guess = scan.nextInt();
scan.nextLine();
attempts++;
}
else {
System.out.println("Your guess was correct!");
attempts++;
System.out.println("Number of guesses: " + attempts);
answer = 0;
}
}
System.out.println("Would you like to play again? (y/n): ");
String input = scan.nextLine();
if (input.equalsIgnoreCase("n")) {
replay = false;
}
}
}
}
while (guess != 0) {
if (guess < answer) {
System.out.println("You guess was too low. Guess again (0 to quit): ");
guess = scan.nextInt();
scan.nextLine();
attempts++;
} else if (guess > answer) {
System.out.println("Your guess was too high. Guess again (0 to quit): ");
guess = scan.nextInt();
scan.nextLine();
attempts++;
} else {
System.out.println("Your guess was correct!");
attempts++;
System.out.println("Number of guesses: " + attempts);
answer = 0;
}
}
You have not nested it wrong, but you don't have a condition that aborts the while loop.
You will set answer to 0, then go back to the beginning of the while loop & find that the guess is now too high because the answer was 0.
I think you wanted to do guess = 0;. Or you could put a break; there too.
As you have
while (guess != 0){
change your code to break out the loop
else {
System.out.println("Your guess was correct!");
attempts++;
System.out.println("Number of guesses: " + attempts);
answer = 0;
break; // add this or change above line to guess = 0;
}
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--;
I'm making a guessing game, all the code works fine except for that I want them to make a number to guess between, I can't seem to figure out how to make it so that if the user inputs a letter like "d" instead of a number like "15" it will tell them they can't do that.
Code:
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
while (true) {
System.out.print("Pick a number: ");
int number = input.nextInt();
if (number != int) {
System.out.println("That's not a number");
} else if (number == int) {
int random = rand.nextInt(number);
break;
}
}
System.out.println("You have 5 attempts to guess the number or else you fail. Goodluck!");
System.out.println("");
System.out.println("Type 'begin' to Begin!");
System.out.print("");
String start = input.next();
if (start.equals("begin")) {
System.out.print('\f');
for(int i=1; i<6; i++) {
System.out.print("Enter a number between 1-" + number + ": ");
int number = input.nextInt();
if (number > random) {
System.out.println("Too Big");
System.out.println("");
} else if (number < random) {
System.out.println("Too Small");
System.out.println("");
} else if (number == random) {
System.out.print('\f');
System.out.println("Correct!");
break;
}
if (i == 5) {
System.out.print('\f');
System.out.println("You have failed");
System.out.println("Number Was: " + random);
}
}
} else if (start != "begin") {
System.out.print('\f');
System.out.println("Incorrect Command");
System.out.println("Please Exit Console And Retry");
}
}
}
use try catch
for example
try{
int a=sc.nextInt();
}catch(Exception e){
System.out.println("not an integer");
}
You could use nextLine() instead of nextInt() and check the out coming String if it matches() the regular expression [1-9][0-9]* and then parse the line with Integer.valueOf(str).
Like:
String str=input.nextLine();
int i=0;
if(str.matches("[1-9][0-9]*"){
i=Integer.valueOf(str);
} else {
System.out.println("This is not allowed!");
}
I hope it helps.
Do something like this:
Scanner scan = new Scanner(System.in);
while(!scan.hasNextInt()) { //repeat until a number is entered.
scan.next();
System.out.println("Enter number"); //Tell it's not a number.
}
int input = scan.nextInt(); //Get your number here