I tried to create basic number find game (1-100).
But always the program terminated after second try.
Code:
Random rnd = new Random();
int rndm = rnd.nextInt(100);
int tryn;
Scanner sc = new Scanner(System.in);
System.out.print("Guess: ");
tryn = sc.nextInt();
if (tryn == rndm) {
System.out.println("You win.");
sc.close();
}
else if (tryn > rndm) {
System.out.println("Too high.");
System.out.print("Guess again: ");
tryn = sc.nextInt();
}
else {
System.out.println("Too low.");
System.out.print("Guess again: ");
tryn = sc.nextInt();
}
When I run output like:
<terminated> test2 [Java Application]...
Guess: 30
Too low.
Guess again: 50
Why my program doesn't loop? Thanks for any help.
Add a loop in your code...
while(tryn != rndm){
Please see the following code (I have tested it):
import java.util.Random;
import java.util.Scanner;
public class Guess {
public static void main(String[] args) {
Random rnd = new Random();
int rndm = rnd.nextInt(100);
int tryn;
Scanner sc = new Scanner(System.in);
System.out.print("Guess: ");
while (sc.hasNextInt()) {
tryn = sc.nextInt();
if (tryn == rndm) {
System.out.println("You win.");
break;
} else if (tryn > rndm) {
System.out.println("Too high.");
System.out.print("Guess again: ");
} else {
System.out.println("Too low.");
System.out.print("Guess again: ");
}
}
sc.close();
}
}
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.");
}
}
}
}
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 am writing a simple guessing game program where the user will input a number to try and guess a randomly generated number.
If they get the number right I want to give them the option to play again.
Here is my code:
public class GuessingGame {
private Random num = new Random();
private int answer = num.nextInt(10);
private int guess;
private String playAgain;
public void inputGuess(){
System.out.println("Enter a number between 1 and 10 as your first guess: ");
Scanner input = new Scanner(System.in);
guess = input.nextInt();
do{
if (guess < 1 || guess > 10){
System.out.println("That is not a valid entry. Please try again: ");
guess = input.nextInt();
}else if (guess > answer){
System.out.println("Too high, Try Again: ");
guess = input.nextInt();
}else if (guess < answer){
System.out.println("Too low, Try Again: ");
guess = input.nextInt();
}
}while (guess != answer);
System.out.println("Congratulations, You guessed the number!");
System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
playAgain = input.nextLine();
if(playAgain == "Y" || playAgain == "y"){
System.out.println("Enter a number between 1 and 10 as your first guess: ");
guess = input.nextInt();
}
}
}
The game plays through but when the user is prompted to play again nothing happens?
Any suggestions?
Here is the completed code, fully working and tested... without using recursion.. and everything fixed.
public static void main(String[] args)
{
String playAgain = "";
Scanner scan = new Scanner(System.in);
do
{
ClassName.inputGuess();
System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
playAgain = scan.nextLine();
}
while(playAgain.equalsIgnoreCase("Y"));
System.out.println("Thanks for playing!");
}
public void inputGuess()
{
Random num = new Random();
int answer = num.nextInt(10)+1;
Scanner input = new Scanner(System.in);
int guess;
System.out.println("Enter a number between 1 and 10 as your first guess: ");
guess = input.nextInt();
do
{
if (guess < 1 || guess > 10)
{
System.out.println("That is not a valid entry. Please try again: ");
guess = input.nextInt();
}
else
if (guess > answer)
{
System.out.println("Too high, Try Again: ");
guess = input.nextInt();
}
else
if (guess < answer)
{
System.out.println("Too low, Try Again: ");
guess = input.nextInt();
}
input.nextLine();
}
while (guess != answer);
System.out.println("Congratulations, You guessed the number!");
}
Do the following and your code will work :
Replace all input.nextInt(); with Integer.parseInt(input.nextLine());
Replace (playAgain == "Y" || playAgain == "y") with (playAgain.equalsIgnoreCase("Y"))
Initialise answer inside inputGuess() in starting instead.
Replace the body of if(playAgain.equalIgnoreCase("Y")) with inputGuess();
When you enter integer value through console it also contain a \n(next line) in it. But when you use nextInt(), it doesn't read this \n, but then when you tried to get next line with input.nextLine(), it looks for \n(next line) which is already there from integer entry and having nothing after that. Code look for "Y" or "y" and breaks because it doesn't found any of them.
That is why Integer.parseInt(input.nextLine()); works here
Here is the code:
private Random num = new Random();
private int answer = num.nextInt(10) +1;
private int guess;
private String playAgain;
Scanner input = new Scanner(System.in);
public void inputGuess(){
System.out.println("Enter a number between 1 and 10 as your first guess: ");
guess = input.nextInt();
do{
if (guess < 1 || guess > 10){
System.out.println("That is not a valid entry. Please try again: ");
guess = input.nextInt();
}else if (guess > answer){
System.out.println("Too high, Try Again: ");
guess = input.nextInt();
}else if (guess < answer){
System.out.println("Too low, Try Again: ");
guess = input.nextInt();
}
if(guess == answer) {
System.out.println("Congratulations, You guessed the number!");
System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
playAgain = input.nextLine();
}
}while (!playAgain.equals("Y") && !playAgain.equals("y"));
}
You just need to introduce the winning/losing logic inside the while, and the condition will be the ending/continue flag.
Another thing is always remember when comparing strings to use the equals method, since the == will compare the object reference and not the String value, in some cases == will return true for equal string since how JVM stores the Strings, but to be sure always use equals.
Try something like this:
public void inputGuess(){
System.out.println("Enter a number between 1 and 10 as your first guess: ");
Scanner input = new Scanner(System.in);
guess = input.nextInt();
playAgain = "Y";
do{
if (guess < 1 || guess > 10){
System.out.println("That is not a valid entry. Please try again: ");
guess = input.nextInt();
}else if (guess > answer){
System.out.println("Too high, Try Again: ");
guess = input.nextInt();
}else if (guess < answer){
System.out.println("Too low, Try Again: ");
guess = input.nextInt();
}
if(guess == answer)
{
System.out.println("Congratulations, You guessed the number!");
System.out.println("Would you like to play again? Enter Y to play or N to quit: ");
input.nextLine();
playAgain = input.next();
answer = num.nextInt(10);
guess = -1;
if(!playAgain.equalsIgnoreCase("N"))
{
System.out.println("Enter a number between 1 and 10 as your first guess: ");
guess = input.nextInt();
}
}
}while (!playAgain.equalsIgnoreCase("N"));
}
You need your code for checking if they want to play again inside the loop. This way you wait until they have guessed the number correctly then ask if they want to play again. If they do you restart the process if they don't you exit the loop.
Some of the solution I see above aren't correct. The random number, you need to add 1 to get between 1 and 10, also you need to compare with equals. I use case insensitive here.
The following code works as you need it.
import java.util.Random;
import java.util.Scanner;
public class Test2 {
private static Random num = new Random();
private static int answer = 0;
private static int guess;
private static String playAgain;
public static void main(String[] args) {
inputGuess();
}
// Guess Method.
public static void inputGuess(){
// create answer.
answer = 1+ num.nextInt(10);
System.out.println("Enter a number between 1 and 10 as your first guess: ");
Scanner input = new Scanner(System.in);
guess = input.nextInt();
do{
if (guess < 1 || guess > 10){
System.out.println("That is not a valid entry. Please try again: ");
guess = input.nextInt();
}else if (guess > answer){
System.out.println("Too high, Try Again: ");
guess = input.nextInt();
}else if (guess < answer){
System.out.println("Too low, Try Again: ");
guess = input.nextInt();
}
}while (guess != answer);
System.out.println("Congratulations, You guessed the number!");
System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
playAgain = input.nextLine();
if( playAgain.equalsIgnoreCase("Y") ){
inputGuess();
}
}
}
By now, you would have already guessed the right way to do it. Here is how I will approach it
public class Test {
public static void main (String...a) {
inputGuess();
}
public static void inputGuess() {
Scanner input = new Scanner(System.in);
String playAgain = "Y";
int guess;
Random ran = new Random();
int answer = ran.nextInt(10) + 1;
while (playAgain.equalsIgnoreCase("Y")) {
System.out.println("Enter a number between 1 and 10 as your first guess: " + answer);
guess = input.nextInt();
do {
if (guess < 1 || guess > 10) {
System.out.println("That is not a valid entry. Please try again: ");
guess = input.nextInt();
} else if (guess > answer) {
System.out.println("Too high, Try Again: ");
guess = input.nextInt();
} else if (guess < answer) {
System.out.println("Too low, Try Again: ");
guess = input.nextInt();
}
} while (guess != answer);
System.out.println("Congratulations, You guessed the number!");
System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
input.nextLine();
playAgain = input.nextLine();
answer = ran.nextInt(10) + 1
}
}
}
This code can serve your purpose...
import java.util.Random;
import java.util.Scanner;
public class GuessingGame
{
private Random num = new Random();
private int answer ;
private int guess;
private String playAgain;
public void inputGuess()
{
answer = num.nextInt(11);
System.out.println("Enter a number between 1 and 10 as your first guess: ");
Scanner input = new Scanner(System.in);
guess = input.nextInt();
do {
if (guess < 1 || guess > 10) {
System.out
.println("That is not a valid entry. Please try again: ");
guess = input.nextInt();
} else if (guess > answer) {
System.out.println("Too high, Try Again: ");
guess = input.nextInt();
} else if (guess < answer) {
System.out.println("Too low, Try Again: ");
guess = input.nextInt();
}
} while (guess != answer);
System.out.println("Congratulations, You guessed the number!");
System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
do
{
playAgain = input.nextLine();
}while(playAgain.length()<1);
if (playAgain.trim().equalsIgnoreCase("y"))
{
inputGuess();
}
else
{
System.out.println("Good Bye!!!");
}
}
public static void main(String[] args) {
new GuessingGame().inputGuess();
}
}
one issue :
Do not compare the content of two strings by == which just
you should use equals()
Imagine the right answer is one in this case
Follow this as your blue print sample
int answer = 0;
String yes = "";
Scanner input = new Scanner(System.in);
do{
do{
System.out.println("Enter your number");
answer = input.nextInt();
} while ( answer != 1);
System.out.println("Would you like to play again?");
yes = input.next();
} while ( yes.equalsIgnoreCase("yes"));
output:
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();
}
}
}