Okay, I want to create a simple game. I input a number, which was generated by PC using Random package and if I guess it, game over. But! I've no idea what is wrong with it.
import java.util.Scanner;
import java.util.Random;
public class Main {
static Scanner read = new Scanner(System.in);
public static void main(String[] args) {
int randomInt = new Random().nextInt(1000);
int userInput = -1;
System.out.println("I guessed a number\nYour turn: ");
while (randomInt != userInput) {
userInput = read.nextInt();
if (randomInt > userInput) {
System.out.println("Less than it");
} else if (randomInt < userInput){
System.out.println("More than that");
}
}
System.out.println("That's right!");
}
}
I used Debug and program worked. I mean, Random did his job, generated a number, but then it didn't show me "That's right!" output when I guessed a number. It just goes like "More that that" and "More that that"...
I ran it myself and it runs as expected. Maybe the confusion comes from the fact that you've switched up the places where you print "Less than it" and "More than that".
It should be like
while (randomInt != userInput) {
userInput = read.nextInt();
if (randomInt > userInput) {
System.out.println("More than that");
} else if (randomInt < userInput){
System.out.println("Less than it");
}
}
You got something wrong with the if statements. Also the scanner should be closed with read.close() to prevent memory leaks. Since there is no reason to put the scanner in the main class I also moved that to the main function. This should work for you know.
import java.util.Scanner;
import java.util.Random;
public class Main {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int randomInt = new Random().nextInt(1000);
int userInput = -1;
System.out.println("I guessed a number\nYour turn: ");
while (randomInt != userInput) {
System.out.println(randomInt);
userInput = read.nextInt();
if (randomInt > userInput) {
System.out.println("More than it");
}
if (randomInt < userInput){
System.out.println("Less than that");
}
}
System.out.println("That's right!");
read.close();
}
}
The console message "More than that" prints if randomInt is less than user input (randomInt < userInput). Wouldn't you want it to print that if it is more than user input? The inverse condition applies to the other message. Could this be the issue? Otherwise, as already suggested, use a print statement to print the number out so you can test the correct guess.
I tried your code, and basically it works. The only problem I see is that you print the wrong string.
import java.util.Scanner;
import java.util.Random;
public class Test {
static Scanner read = new Scanner(System.in);
public static void main(String[] args) {
int randomInt = new Random().nextInt(10);
int userInput = -1;
System.out.println("I guessed a number\nYour turn: ");
while (randomInt != userInput) {
userInput = read.nextInt();
if (randomInt > userInput) {
System.out.println("More than it");
} else if (randomInt < userInput) {
System.out.println("Less than that");
}
}
System.out.println("That's right!");
}
}
Some tips:
Do not use such big numbers for tests
Instead of using a while loop use a do while loop
Related
new to programming.
I have a class in java and i'm trying to write this program but it's printing none-stop and it's even bugging my browser! (Im using an online ide)
my instructions:
Q: how much do you love me?
Below 10 : wrong answer
equal to 10 and more = good answer
I know how to do it but I dont want the program to stop every time i write an answer. I want the program to keep running until i have a 10 +. So i can always input until it's 10+ out of 10.
this is my lines :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println ("how much do you love me out of 10");
int num1 = input.nextInt();
while (true)
if (num1 <= 9) {
System.out.println("Wrong answer");
}
else {
System.out.println ("Good answer");
}
}
}
This should work:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
System.out.println ("Out of 10, how much do you love me?");
int input = 0
while (input <= 9) {
input = scanner.nextInt();
if (input <= 9) {
System.out.println("Wrong answer");
} else {
System.out.println("Good answer");
}
}
}
}
Explanation: It loops until input is less not less than or equal to 9 (while (input <= 9)). Each time through the loop, it gets input and acts on it.
Hope this helps!
First off, you need to move the int num1 = input.nextInt(); statement inside your while loop, this will allow for a new input every time the while loop loops (iterates).
Second, if you are looking to run the program until num1 >= 10, then you could implement it in two ways.
while(num1 < 10) {
num1 = input.nextInt();
if(num1 >= 10) {
System.out.println("Good answer");
} else {
System.out.println("Wrong answer");
}
}
or using the keyword break,
while(true) {
num1 = input.nextInt();
if(num1 >= 10) {
System.out.println("Good answer");
break;
} else {
System.out.println("Wrong answer");
}
}
break simply escapes the loop it resides in when called
Hoped this helped
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 can't seem to be able have my program ask the user if they would like to play again. The program ends when asking if they would like to continue. I added a break because before the program was continuously looping the correct answer and number of tries.
import java.util.Random;
import java.util.Scanner;
public class GuessTheNumber {
public static void main(String[] args) {
boolean play = true;
Scanner input = new Scanner(System.in);
Random Number = new Random();
int GuessNumber = 1+ Number.nextInt(1000);
int guess = 0;
int Tries = 0;
while(play) {
while(guess != GuessNumber) {
System.out.println("Please Enter a number between 1 and 1000:");
guess = input.nextInt();
Tries++;
if(guess == GuessNumber) {
System.out.println("You Win!");
break;
}
else if(guess < GuessNumber) {
System.out.println("Guess is too low");
}
else if(guess > GuessNumber) {
System.out.println("Guess is too high");
}
}
System.out.printf("Number was: %d",GuessNumber);
System.out.println("");
System.out.printf("Number of tries was: %d ",Tries);
System.out.println("");
System.out.println("Would you like to play again?(Yes/No)");
String playagain = input.nextLine();
if("Yes".equals(playagain))
play = true;
else
play = false;
}
}
}
A few things with your program.
As the comments have noted, you do need to flush your new-line character after using nextInt().
But, you must also set the guess value and try-count back to 0 after the user states that they would like to play again -- otherwise the program will just continue in a "You win!" loop.
I would recommend moving your variable declarations to the outer loop:
while(play) {
int guess = 0;
int guessNumber = 1 + Number.nextInt(1000);
int tries = 0;
...
}
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();
}
}
}