I am working on a simple game in which the user has to guess a random number. I have all the code set up except for that fact that if the guess is too high or too low I don't know how to allow them to re-enter a number and keep playing until they get it. It just stops; here is the code:
import java.util.Scanner;
import java.util.Random;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
int random = rand.nextInt(10) + 1;
System.out.print("Pick a number 1-10: ");
int number = input.nextInt();
if (number == random) {
System.out.println("Good!");
} else if (number > random) {
System.out.println("Too Big");
} else if (number < random) {
System.out.println("Too Small");
}
}
}
In order to repeat anything you need a loop.
A common way of repeating until a condition in the middle of loop's body is satisfied is building an infinite loop, and adding a way to break out of it.
Idiomatic way of making an infinite loop in Java is while(true):
while (true) {
System.out.print("Pick a number 1-10: ");
int number = input.nextInt();
if (number == random) {
System.out.println("Good!");
break; // This ends the loop
} else if (number > random) {
System.out.println("Too Big");
} else if (number < random) {
System.out.println("Too Small");
}
}
This loop will continue its iterations until the code path reaches the break statement.
You need to use a loop for that. The code should work like this:
import java.util.Scanner;
import java.util.Random;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
int random = rand.nextInt(10) + 1;
System.out.print("Pick a number 1-10: ");
int number = input.nextInt();
boolean found = false;
while (!found) {
if (number == random) {
System.out.println("Good!");
found = true;
} else if (number > random) {
System.out.println("Too Big, try again:");
number = input.nextInt();
} else if (number < random) {
System.out.println("Too Small, try again:");
number = input.nextInt();
}
}
}
}
You could use a do...while.
Random rand = new Random();
int random = rand.nextInt(10) + 1;
do {
Scanner input = new Scanner(System.in);
System.out.print("Pick a number 1-10: ");
int number = input.nextInt();
if (number == random) {
System.out.println("Good!");
} else if (number > random) {
System.out.println("Too Big");
} else if (number < random) {
System.out.println("Too Small");
}
} while ( number != random );
Several techniques exist to loop your request, among them:
while (<condition>) { <do something> }
do { <something> } while (<condition>);
for (<init statement>, <condition>, <update statement>) { <do something> }
To show off, you can avoid using one of the above explicit loop constructs by using recursion:
mport java.util.Scanner;
import java.util.Random;
public class Test {
public static void ask(int random) {
Scanner input = new Scanner(System.in);
System.out.print("Pick a number 1-10: ");
int number = input.nextInt();
if (number == random) {
System.out.println("Good!");
} else if (number > random) {
System.out.println("Too Big");
ask(random);
} else if (number < random) {
System.out.println("Too Small");
ask(random);
}
}
public static void main(String[] args) {
Random rand = new Random();
int random = rand.nextInt(10) + 1;
ask(random);
}
}
Here the ask() method keeps calling itself, until the end condition (user guessed right) is reached.
Depending on the cleverness of the Java virtual machine this might stress the call stack, or not.
Enclose the if statements within a do-while loop, that will loop around while the user hasn't guessed the number:
int number;
do {
System.out.print("Pick a number 1-10: ");
number = input.nextInt();
if (number == random) {
System.out.println("Good!");
} else if (number > random) {
System.out.println("Too Big");
} else if (number < random) {
System.out.println("Too Small");
}
} while (number != random);
In order to repeat code conditionally, use a loop.
// this code will execute only once
System.out.print("Pick a number 1-10: ");
// initialize number to a value that would not be used and not equal random
int number = -1;
// the code inside the curly braces will repeat until number == random
while (number != random) {
// get next number
number = input.nextInt();
// handle case one
if(number > random) System.out.println("Too Big");
// handle case two
if(number < random) System.out.println("Too Small");
}
// once number == random, the condition is false so we break out of the loop
System.out.println("Good!");
What you're looking for are constructs in the programming language that allow you do a specific thing again and again.
This is done using loops.
Check the docs for the while loop for instance. That's what you need.
Related
Hello everyone I'm still new in java but I was trying to do this guess game that has 2 levels first one in a normal guess game the second level is that the user has 5 attempts to guess the number but each time he/she fails it generates a new random number but I can't link the 2 levels together when I pass the first level it gets me to the second but with the conditions of the first and doesn't generate a random number each attempt I hope you guys have the knowledge to let me know what kind of mistakes I made
package guessing_game;
import java.util.Random;
public class Game {
Random random = new Random();
private boolean gameOver;
private int secretNumber;
private int numberOfGuess;
public Game(int range) {
gameOver = false;
secretNumber = random.nextInt(10);
numberOfGuess = 0;
}
public boolean isGameOver() {
return gameOver;
}
public boolean guess(int n) {
if (gameOver) {
System.out.println("The game is over. "
+ "You can not guess again.");
} else if (n == secretNumber) {
System.out.println("You guessed right!"
+"let's go to next level.");
gameOver = false;
} else {
if (n < secretNumber) {
System.out.println("Your guess is too low.");
} else {
System.out.println("Your guess is too high.");
}
numberOfGuess++;
if (numberOfGuess == 5) {
System.out.println("You have used up all of your guesses.");
gameOver = true;
}
}
return gameOver;
}
public void guess2(int n){
if (gameOver) {
System.out.println("The game is over. "
+ "You can not guess again.");
} else if (n == secretNumber) {
System.out.println("You guessed right!");
gameOver = true;
} else {
if (n < secretNumber) {
System.out.println("Your guess is not right.");
secretNumber=random.nextInt(10);
} else {
System.out.println("Your guess is not right.");
secretNumber=random.nextInt(10);
}
numberOfGuess++;
if (numberOfGuess == 5) {
System.out.println("You have used up all of your guesses.");
gameOver = true;
}
}
}
}
package guessing_game;
import java.util.Scanner;
public class Guessing_game {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Game theGame = new Game(10);
while(theGame.isGameOver() == false){
System.out.println("Guess a number between 0 and 10:");
int n = input.nextInt();
theGame.guess(n);
if(theGame.guess(n)==false)
theGame.guess2(n);
}
}
}
Break the problem down into the steps you described.
You have two levels for guessing random a number.
First level: infinite guesses of a fixed random number
Second level: max 5 guesses of a random number that changes with each guess
Something like
public class Game {
public boolean play() {
Random random = new Random();
int level = 1;
int secretNumber = random.nextInt(10); // random number for all of level 1
// infinite guesses for level 1
do {
int guess = ... // get user input from keyboard
if (guess == secretNumber) {
level++;
}
} while (level == 1);
// level 2, only five guesses
for (int i = 0; i < 5; i++) {
// level 2, random number changes at each failed guess
secretNumber = random.nextInt(10);
int guess = ... // get user input from keyboard
if (guess == secretNumber) {
return true; // they won the game
}
}
return false; // they lost
}
}
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.
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int rnd = (int)(Math.random() * 101);
System.out.println("The program is going to give a number that is between 0 and 100 (including them). You can guess it by pressing Run.");
System.out.println("Enter your number:");
int num = scan.nextInt();
for (int count = 1; count <= 7; count++) {
while (num != rnd) {
if (num < rnd) {
System.out.println("Your guess is too low.");
}
if (num > rnd) {
System.out.println("Your guess is too high.");
}
if ((Math.abs(rnd - num) == 1) || (Math.abs(rnd - num) == 2)) {
System.out.println("But your guess is VERY close.");
}
num = scan.nextInt();
}
System.out.println("You got it right!");
}
System.out.println("You should guess it in 7 tries.");
}
}
So I used two loops and just nested them. Is that how it works for this? Right now the code is like starting with for loop and if that is true it goes to the while loop part where the guessing number takes place. Can this be fixed with just moving some codes and fixing minor areas around?
What you should do in a situation like this is do the code manually. Literally. Grab a piece of paper and pretend you're a computer. It's a good exercise, and it will help you figure out your problem.
The problem is your inner loop. It loops until they guess correctly regardless of the number of attempts. Then you force them to do it 6 more times with the outer loop.
You really only need 1 loop. I would have a single loop like this:
int attempts = 0;
int num = 0;
do {
num = scan.nextInt();
... most of the if code from your inner loop but not another scan.nextInt
} while (++attempts < 7 && num != rnd);
// and here you look at num == rnd to see if success or failures
I think you should rebuild you code to make it more clear.
Split the title (with description of the task)
Split main loop where you read user input and check it with expected number
Split output of the final result, where you print the result.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
final int rnd = new Random().nextInt(101);
final int maxAttempts = 7;
System.out.println("The program is going to give a number that is between 0 and 100 (including them).");
System.out.println("You can guess it within maximum " + maxAttempts + " attempts by pressing Run.");
boolean success = false;
for (int attempt = 1; attempt <= maxAttempts && !success; attempt++) {
System.out.format("(%s of %s) Enter your number: ", attempt, maxAttempts);
int num = scan.nextInt();
if (num == rnd)
success = true;
else {
System.out.print("Your guess is too " + (num > rnd ? "high" : "low") + '.');
System.out.println(Math.abs(rnd - num) <= 2 ? " But it's VERY close." : "");
}
}
System.out.println(success ? "You got it right!" : "Bad luck this time. Buy.");
}
import java.util.Scanner;
class Main {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int rnd = (int) (Math.random() * 101);
System.out.println("The program is going to give a number that is between 0 and 100 (including them). You can guess it by pressing Run.");
System.out.println("Enter your number:");
int num = scan.nextInt();
for(int count = 1; count <= 7; count++)
{
if (num < rnd)
{
System.out.println("Your guess is too low.");
}
else if (num > rnd)
{
System.out.println("Your guess is too high.");
}
else if ((Math.abs(rnd - num) == 1) || (Math.abs(rnd - num) == 2))
{
System.out.println("But your guess is VERY close.");
}
else
System.out.println("You got it right!");
System.out.println("Enter Next number: ");
num = scan.nextInt();
}
}
}
It should work Fine.Basically Your reasoning wass wrong because You are putting a while loop inside a for loop. What you want to do is you want only 7 iteration.In those 7 iterations you are checking the conditions based on user Input.
I've been trying to figure this out for hours but I can't for some reason my output just shows "Sorry that number is too high" and "Sorry that number is too low" at the same time without looping or using a single answer.
import java.util.*;
public class RandomNumbers {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Random numGen = new Random();
int RanNum = numGen.nextInt(20) + 1;
System.out.println("Guess what number im thinking of");
int num ;
num = keyboard.nextInt();
if (num == RanNum)
System.out.println("Good Job");
else if (num > RanNum)
System.out.println("Sorry that number is too high");
else if (num < RanNum);
System.out.println("Sorry that number is too low");
}
}
Semicolon after else if (num < RanNum) is your problem
you misplaced a semicolon at the end of your third if.
You should still get the Good Job message though.
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
Random numGen = new Random();
int RanNum = numGen.nextInt(1) + 1;
System.out.println("Guess what number im thinking of");
int num ;
num = keyboard.nextInt();
if (num == RanNum)
System.out.println("Good Job");
else if (num > RanNum)
System.out.println("Sorry that number is too high");
else if (num < RanNum)
System.out.println("Sorry that number is too low");
}
edit: sorry, too late :)
To keep prompting the user use a while loop to check whether they guessed correct or not. I would also recommend adding another input check for exiting without getting it correct. Brief example:
boolean incorrect = true;
while(incorrect) {
//Code to prompt for input
if(userIsCorrect || input == -1){
incorrect = false;
//Program will exit loop when this is set to false
}
}
the application is a simple guessing game which i got that part down. my issue is making a method that before any guessing starts the player must first guess the right amount of digits in a number
e.g the guess being 314 and the answers has 3 digits in it then the guessing of too high two low starts otherwise it keeps looping until you guess the right amount of digits.
now i have created the method to do this my issue is a rather simple one i think but its a matter of initializing the variables and that's where i am having problems.
import java.util.Random;
import java.util.Scanner;
public class NumberGuess
{
public static void main (String[] args)
{
final int MAX = 1000;
int answer, guess;
Scanner Keyboard = new Scanner(System.in);
Random generator = new Random(); //Random generator. 1 to 100.
answer = generator.nextInt(MAX) +1;
guess = Keyboard.nextInt();
System.out.print ("I'm thinking of a number between 1 and "+ MAX + ". Guess what it is: (or enter 0 to quit) ");
do
{
System.out.print("Guess what the number is: ");
guess = Keyboard.nextInt();
if (guess > answer && guess != 0)
System.out.println("Your guess is too high!");
else if (guess < answer && guess !=0)
System.out.println("Your guess is too low!");
if(guess==0)
System.out.println("you have ended your game");
else if (guess == answer)
System.out.println("You got it!");
} while (guess != answer&& guess!=0);
}
int NumOfDigits(int number)
{
int numDigits = 0;
while (number/10 > 0);
{
number = number/10;
numDigits++;
}
return numDigits;
}
int guess;
Scanner Keyboard1 = new Scanner(System.in);
guess = Keyboard1.nextInt();
int target = NumOfDigits(answer);
while(NumOfDigits(guess) != target);
{
System.out.println("read anothrer input guess");
guess = Keyboard1.nextInt();
}
System.out.println("you got the correct number of digits now guess the number!");
guess = Keyboard1.nextInt();
}
your method for counting diigits is wrong it should be like this
public static int NumOfDigits(int number)
{
int numofdigits = 0;
while(number>0){
numofdigits++;
number = number/10;
}
return numofdigits;
}
because your method returns 2 and it should return 3