Ok so I've tried one method but it kept showing "Do you want to play again" every time i entered a number for some reason. Here is what I have so far. What else could i do to so that only after the user guesses the correct answer it asks if he/she wants to play again?
import java.util.Random;
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random rand = new Random();
int number = rand.nextInt(100) + 1;
int guess;
System.out.println("Guess the number between 1 and 100\n");
guess = scan.nextInt();
while (true) {
if(guess < number)
System.out.println("Higher!");
else if(guess > number)
System.out.println("Lower!");
else if (guess == number){
System.out.println("Correct!");
}
guess = scan.nextInt();
}
}
}
Try out this
class GuessNumber {
static Random rand = new Random();
static Scanner scan = new Scanner(System.in);
static int number;
public static void main(String[] args) {
playGame();
}
public static void playGame() {
number = rand.nextInt(100) + 1;
System.out.println("Guess the number between 1 and 100");
while (true) {
int guess = scan.nextInt();
if (guess < number) {
System.out.println("Higher!");
} else if (guess > number) {
System.out.println("Lower!");
} else if (guess == number) {
System.out.println("Correct!");
System.out.println("Do you like to play again?[1 for Yes/0 for No]");
int val = scan2.next();
if (val == 1)
playGame();
else
break;
}
}
}
}
or rather than using same scanner you can use another scanner and get string input as follows
else if (guess == number) {
System.out.println("Correct!");
Scanner scan2 = new Scanner(System.in);
System.out.println("Do you like to play again?[Y/N]");
String val = scan2.next();
if (val.equalsIgnoreCase("Y"))
playGame();
else
break;
}
You need to exit the while when correct.
To do so, after the line:
System.out.println("Correct!");
Add another line like this:
break;
Mostly out of fun, I implemented a game that fits the description of what you were trying to do. The code is not the cleanest / most efficient, but it definitely works!
Take a look at it and see if you can figure out your problem.
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
System.out.println("Guess the number between 1 and 100");
playGuessingGame();
while (true) {
System.out
.println("Do you want to play again? Type y / n and hit enter");
Scanner scan = new Scanner(System.in);
String playAgain = scan.next();
if (playAgain.charAt(0) == 'y') {
System.out.println("Okay, I picked a new number. Good luck!");
playGuessingGame();
} else {
System.out.println("Thanks for playing!");
break;
}
}
}
public static void playGuessingGame() {
Scanner scan = new Scanner(System.in);
Random rand = new Random();
int guess;
int number = rand.nextInt(100) + 1;
guess = scan.nextInt();
while (guess != number) {
if (guess < number)
System.out.println("Higher!");
else if (guess > number)
System.out.println("Lower!");
else if (guess == number) {
System.out.println("Correct!");
}
guess = scan.nextInt();
}
}
}
Related
I'm working on a homework problem of creating a guessing game. I've got that part working, but we have to validate the input. I've tried using hasNextInt, but I keep getting an error saying "int cannot be dereferenced" and points to the "!guess.hasNextInt" code.
I've tried many iterations, but I still get the same error. The code I'm including is just my most recent try.
How do I get hasNextInt to work or how else should I validate the input?
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
int num = (int) (Math.random() * 101);
Scanner input = new Scanner(System.in);
System.out.println("Welcome to my Guessing Game!");
int guess = -1;
//Loop goes as long as guess doesn't equal num
while (guess != num) {
System.out.print("Guess a number between 1 and 100: ");
guess = input.nextInt();
//Validates input
while (!guess.hasNextInt()) {
System.out.println("Invalid response, try again.");
in.next();
}
if (guess == num)
System.out.println("Correct!");
else if (guess < num)
System.out.println("Your guess was too low");
else
System.out.println("Your guess was too high");
}
}
}
i fixed the code:
public static void main(String[] args) {
int num = (int) (Math.random() * 101);
System.out.println(num);
Scanner input = new Scanner(System.in);
System.out.println("Welcome to my Guessing Game!");
int guess = -1;
//Loop goes as long as guess doesn't equal num
while (guess != num) {
System.out.print("Guess a number between 1 and 100: ");
guess = input.nextInt();
if (guess == num) {
System.out.println("Correct!");
break;}
else if (guess < num)
System.out.println("Your guess was too low");
else
System.out.println("Your guess was too high");
//Validates input
while (!input.hasNextInt()) {
System.out.println("Invalid response, try again.");
input.next();
}
}
}
if the user guessed the number the game ends using break
in while (!guess.hasNextInt()) you were using a integer where it's expect the Scanner input
If you want to parse your number you can use Integer.parseInt() method as shown. Also you are using hasNextInt() incorrectly. You are also not storing in.next() value in any variable.
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
int num = (int)(Math.random() * 101);
Scanner input = new Scanner(System.in);
System.out.println("Welcome to my Guessing Game!");
int guess = -1;
//Loop goes as long as guess doesn't equal num
while (true) {
System.out.print("Guess a number between 1 and 100: ");
String numberString = input.nextLine();
//Validates input
try {
guess = Integer.parseInt(numberString);
if (guess == num) {
System.out.println("Correct!");
break;
} else if (guess < num)
System.out.println("Your guess was too low");
else
System.out.println("Your guess was too high");
} catch (Exception e) {
System.out.println("Invalid response, try again.");
}
}
}
}
For my Java class, I'm supposed to make a random number guessing game. I've been stuck on a loop I created for the past couple of days. The output of the program is always an infinite loop and I can't see why. Any help is very much appreciated.
/*
This program will generate a random number.
It will ask the user to guess what number was generated and say
if the guess is too high or low.
*/
import java.util.Scanner;
import java.util.Random;
public class RandomNumGame {
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int randNum = rand.nextInt(20);
System.out.println("Number is : " + randNum);
int userGuess = 0;
int success = 0;
System.out.println("Guess the number: ");
userGuess = input.nextInt();
while(success == 0)
{
if(userGuess > randNum){
System.out.println("Too high");
}
else if(userGuess < randNum){
System.out.println("Too high");
}
else{
System.out.println("Something is very wrong.");
}
}
if(userGuess == randNum){
success++;
System.out.println("You got it! Play again?");
}
}
}
You put the if that checks if the input is equal to the number outside the while, so the cycle never ends.
Here is the code fixed:
import java.util.Scanner;
import java.util.Random;
public class RandomNumGame {
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int randNum = rand.nextInt(20);
System.out.println("Number is : " + randNum);
int userGuess = 0;
int success = 0;
System.out.println("Guess the number: ");
userGuess = input.nextInt();
while(success == 0) {
if(userGuess > randNum) {
System.out.println("Too high");
} else if(userGuess < randNum) {
System.out.println("Too high");
} else if(userGuess == randNum) {
success++;
System.out.println("You got it! Play again?");
} else {
System.out.println("Something is very wrong.");
}
}
}
}
I fixed it! I added breaks after each fail condition so that I wouldn't get an infinite loop. I tried this earlier, but I kept getting errors.
This is the completed code:
import java.util.Scanner;
import java.util.Random;
public class RandomNumGame {
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int randNum = rand.nextInt(20);
System.out.println("Number is : " + randNum);
int userGuess = 0;
boolean success = false;
System.out.println("Guess the number: ");
userGuess = input.nextInt();
input.close();
while(success == false){
if(userGuess > randNum) {
System.out.println("Too high,try again");
break;
} else if(userGuess < randNum) {
System.out.println("Too low");
break;
} else if(userGuess == randNum) {
success = true;
System.out.println("You got it! Play again?");
} else {
System.out.println("Something is very wrong.");
}
}
}
}
I am new to coding. I created a guessing game, and it works well but, I would like to know how to make it so that after the user attempts guessing the number 3 times, they get a hint which I put on the last line, but it is currently unreachable, and I do not know how to make the statement reachable, and in the do while loop. I am currently stuck. Thank you
import java.util.Scanner;
public class guessing_game {
public static void main (String[] args) {
Scanner kb = new Scanner(System.in);
desc();
run(kb);
//int nun = 0;
//for (int i = 0; i < nun; nun ++)
}
public static void desc() {
System.out.println("This is a guessing game.");
System.out.println();
System.out.println("Let's see how many tries it takes you to guess the right number!");
System.out.println();
System.out.println();
System.out.println();
}
public static int run(Scanner kb) {
System.out.println("Please enter a number between 1-100");
int guess = kb.nextInt();
int num = 44;
int tries = 0;
do {
if (guess < num) {
System.out.println("Oooh. Your guess is too low. Try again.");
System.out.println();
run(kb);
}
else if ((guess > 100) || (guess < 0)) {
System.out.println("That isn't between 1-100 is it?");
System.out.println();
run(kb);
}
else if (guess > num) {
System.out.println("Aaah. Your guess is too high. Try again.");
System.out.println();
run(kb);
}
else if(guess == num) {
System.out.println("Bingo!!! Nice guess bud.");
System.out.println("Tell a friend to play! Wanna try again? (y or n)");
String choice = kb.next();
if (choice.equalsIgnoreCase("y")) {
run(kb);
}
else if (choice.equalsIgnoreCase("n")) {
System.exit(0);
}
}
tries++;
}while(tries < 3);
{
System.out.print("Here's a hint the lucky number is 4");
}
return guess;
}
}
There are a few flow issues with your program, but here is a simple way to fix it up.
First of all, you are not actually using the value of guess when you return it from your run() method, so that can be removed.
Also, in cases like this, you would not want to use a do/while loop, but just while. You want to keep repeating the prompt until the user guesses correctly. So add a boolean to allow you to check if they won:
boolean correct = false; - We set it false to begin because they haven't won yet.
Now, instead of calling run() again after every guess (which resets the tries count every time, just let the while loop do its job and repeat itself. Hence, we need to move the prompt input into the while loop.
Here is a complete code listing of the changes:
import java.util.Scanner;
public class guessing_game {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
desc();
run(kb);
//int nun = 0;
//for (int i = 0; i < nun; nun ++)
}
public static void desc() {
System.out.println("This is a guessing game.");
System.out.println();
System.out.println("Let's see how many tries it takes you to guess the right number!");
System.out.println();
System.out.println();
System.out.println();
}
// Change the return type to void as you never use the value returned
public static void run(Scanner kb) {
int num = 44;
// Add a boolean to determine if the game is won
boolean correct = false;
int tries = 0;
while (!correct) {
System.out.println("Please enter a number between 1-100");
int guess = kb.nextInt();
if (guess < num) {
System.out.println("Oooh. Your guess is too low. Try again.");
System.out.println();
} else if ((guess > 100) || (guess < 0)) {
System.out.println("That isn't between 1-100 is it?");
System.out.println();
} else if (guess > num) {
System.out.println("Aaah. Your guess is too high. Try again.");
System.out.println();
} else if (guess == num) {
// Flag the guess as correct; this will exit the loop after this run
correct = true;
System.out.println("Bingo!!! Nice guess bud.");
System.out.println("Tell a friend to play! Wanna try again? (y or n)");
String choice = kb.next();
if (choice.equalsIgnoreCase("y")) {
run(kb);
} else if (choice.equalsIgnoreCase("n")) {
System.exit(0);
}
}
tries++;
}
}
}
1.You are recursively calling run() method and every time you call this method, a new variable try will be created and initialised to zero.
2. Your recursive call is before the condition check and due to the same reason the logic may never reach the condition check.
To make this work with minimal changes, you can use the following code. But this is not the best as it does not resolve the above shortcomings
import java.util.Scanner;
public class guessing_game {
static int tries = 0;
public static void main (String[] args)
{
Scanner kb = new Scanner(System.in);
desc();
run(kb);
//int nun = 0;
//for (int i = 0; i < nun; nun ++)
}
public static void desc()
{
System.out.println("This is a guessing game.");
System.out.println();
System.out.println("Let's see how many tries it takes you to guess the right number!");
System.out.println();
System.out.println();
System.out.println();
}
public static int run(Scanner kb)
{
System.out.println("Please enter a number between 1-100");
int guess = kb.nextInt();
int num = 44;
do{
tries++;
if(tries>=3) break;
if (guess < num)
{
System.out.println("Oooh. Your guess is too low. Try again.");
System.out.println();
run(kb);
}
else if ((guess > 100) || (guess < 0))
{
System.out.println("That isn't between 1-100 is it?");
System.out.println();
run(kb);
}
else if (guess > num)
{
System.out.println("Aaah. Your guess is too high. Try again.");
System.out.println();
run(kb);
}
else if(guess == num)
{
System.out.println("Bingo!!! Nice guess bud.");
System.out.println("Tell a friend to play! Wanna try again? (y or n)");
String choice = kb.next();
if (choice.equalsIgnoreCase("y"))
{
run(kb);
}
else if (choice.equalsIgnoreCase("n"))
{
System.exit(0);
}
}
}while( tries < 3);
{
System.out.print("Here's a hint the lucky number is 4");
}
return guess;
}
}
When I compile, that try to enter (y) to play again my do - while is not working, it takes me out of the loop.
import java.util.Scanner;
public class HiLo {
public static void main(String[] args) {
// Creating a play again variable
String playAgain = "";
// Create Scanner object
Scanner scan = new Scanner(System.in);
// Create a random number for the user to guess
int theNumber = (int)(Math.random() * 100 + 1);
int guessNumber = 0;
do
{
System.out.println("Guess a number between 1 - 100: ");
while (guessNumber != theNumber)
{
guessNumber = scan.nextInt();
if (guessNumber > theNumber)
{
System.out.println("Sorry, try again too high!");
}
else if (guessNumber < theNumber)
{
System.out.println("Sorry, try again too low!");
}
else
{
System.out.println("Congrats, you got it!");
}
}
System.out.println("Would you like to play again (y/n)?");
playAgain = scan.next();
} while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing! Goodbye.");
scan.close();
}
}
Change the code as below: (You just need to update the variables inside the loop)
public static void main(String[] args) {
// Creating a play again variable
String playAgain = "";
// Create Scanner object
Scanner scan = new Scanner(System.in);
// Create a random number for the user to guess
int theNumber = 0;
int guessNumber = 0;
do
{
// new lines to be added
theNumber = (int)(Math.random() * 100 + 1);
guessNumber = 0;
System.out.println("Guess a number between 1 - 100: ");
while (guessNumber != theNumber)
{
guessNumber = scan.nextInt();
if (guessNumber > theNumber)
{
System.out.println("Sorry, try again too high!");
}
else if (guessNumber < theNumber)
{
System.out.println("Sorry, try again too low!");
}
else
{
System.out.println("Congrats, you got it!");
}
}
System.out.println("Would you like to play again (y/n)?");
playAgain = scan.next();
} while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing! Goodbye.");
scan.close();
}
Here is the execution of code on Jshell:
The reason the program is not working is because the do-while loop does one iteration before it gets to the "while" part. In your case, the program successfully finishes the loop after a user correctly guesses the number. Your program breaks because after that you are requiring the user to enter 'y' to continue endlessly without letting them guess a number. If they guess a number, the program terminates.
I have created a simple project for my self, and now i am trying to integrate a code that will make the program restart when i enter "restart" in the console. To do that I have created a second method in my program that contains exactly the same code as my main method but now i want to appoint the second method which i don't know how to do. All help is appreciated!
here is my code so far:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("guess the number between 1 and 9");
int random = (int)(Math.random() * 9 + 1);
int value = 0;
do{
value = scanner.nextInt();
if (value != random){
System.out.println("Try again");
}
}
while(value != random);
System.out.println("You guessed the number");
if(value == random){
System.out.println("Would you like to restart?");
String reset = scanner.nextLine();
if (reset.equals("restart")){
/*
*I need some code here
*/
}
}
}
public static void restart(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("guess the number between 1 and 9");
int random = (int)(Math.random() * 9 + 1);
int value = 0;
do{
value = scanner.nextInt();
if (value != random){
System.out.println("Try again");
}
}
while(value != random);
System.out.println("You guessed the number");
if(value == random){
System.out.println("Would you like to restart?");
String reset = scanner.nextLine();
if (reset.equals("restart")){
}
}
}
You should just call main() in "if (reset.equals("restart")){..."
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("guess the number between 1 and 9");
int random = (int)(Math.random() * 9 + 1);
int value = 0;
do{
value = scanner.nextInt();
if (value != random){
System.out.println("Try again");
}
}
while(value != random);
System.out.println("You guessed the number");
if(value == random){
System.out.println("Would you like to restart?");
String reset = scanner.nextLine();
if (reset.equals("restart")){
main(args); // restart you code
return;
}
}
}
or use following code:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
do{
System.out.println("guess the number between 1 and 9");
int random = (int)(Math.random() * 9 + 1);
int value = 0;
do{
value = scanner.nextInt();
if (value != random){
System.out.println("Try again");
}
}
while(value != random);
System.out.println("You guessed the number");
System.out.println("Would you like to restart?");
String reset = scanner.nextLine();
}
while(reset.equals("restart"));
}
Try something like this,
In your code,
you have been mess up code, and need to break down according to requirement, a
Also, need to take care if user want to restart then again game will be played.
This things overcome by below code,
static int value;
static int random = (int)(Math.random() * 9 + 1);
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
do{
System.out.println("Enter Your Guesses :");
value = scanner.nextInt();
if(value == random){
System.out.println("Exactly Match : " + value + " == " + random);
System.out.println("Would you like to restart?");
String reset = scanner.next();
if (reset.equals("restart")){
restart();
}
}else{
System.out.println("Try again");
}
}while(value != random);
System.out.println("You guessed the number");
}
public static void restart(){
do{
random = (int)(Math.random() * 9 + 1);
}while(value == random);
}