Random numbers in Java loops and if statements - java

I am writing a program where the user enters a number and the computer guesses the number.
I'm having trouble with my else/if statement inside of my while loop. The problem is it prints out "guess higher" but the computer does not always guess higher. I'm not sure how to go about this problem.
while(computerGuess != userGuess) {
if(computerGuess > userGuess) {
System.out.println("Guess lower: ");
computerGuess = guess.nextInt(userGuess);
System.out.println(computerGuess);
}else if(computerGuess < userGuess) {
System.out.println("Guess higher: ");
computerGuess = guess.nextInt(101);
System.out.println(computerGuess);
}
amountTries++;
}

The problem is it prints out "guess higher" but the computer does not
always guess higher. I'm not sure how to go about this problem.
You are specifying a hard-coded limit of 101 for the random number generation. But in the case where the computer guess is smaller than the user value, you need to have a random number generated between the computer guess and the user guess.
Replace
computerGuess = guess.nextInt(101);
with
computerGuess = guess.nextInt(userGuess - computerGuess) + computerGuess + 1;

If you are trying to build a program where computer guesses the number by binary search logic then your code is not going to work. Following code will perform binary search kind of logic.
int i=0;int j=101;
while(computerGuess != userGuess) {
if(computerGuess > userGuess) {
j=computerGuess;
System.out.println("Guess lower: ");
computerGuess = guess.nextInt(j);
System.out.println(computerGuess);
}else if(computerGuess < userGuess) {
i=computerGuess;
System.out.println("Guess higher: ");
//computerGuess = guess.nextInt(101);
computerGuess = guess.nextInt(j - i) +i;
System.out.println(computerGuess);
}
amountTries++;
}
PS: Not tested for corner cases. Code is just to provide a basic idea.

Related

Java High-Low Guessing Game Looping Errors

I've just started learning programming for the first time and I am working through Java to start. I am doing a common coding exercise of programming a guessing game using loops and conditionals. My program is required to do the following:
Pick a random number between 1 and 100
Repeatedly prompt the user to guess the number
Report to the user that he or she is correct or that the guess is high
or low after each guess
Offer the user the option to quit mid-game
Count the number of guesses in a game and report the number upon a correct guess
Ask the user if they want to play again upon a successful game
I have been a little bit shaky with loop syntax so far and need some help with my program because there are a lot of issues I don't know how to fix. Would anyone be kind enough to lend me a hand? Please forgive the many probably obvious mistakes.
import java.util.Scanner;
import java.util.Random;
public class Guess
{
public static void main (String[] args)
{
final int MAX = 100;
int answer, guess = 0, count = 0;
String another = "y";
Random generator = new Random();
answer = generator.nextInt(MAX) + 1;
Scanner scan = new Scanner(System.in);
System.out.println("I'm thinking of a number between 1 and " + MAX
+ ". Guess what it is: ");
guess = scan.nextInt();
while (another.equalsIgnoreCase("y"))
{
while (guess != answer)
{
while (guess > MAX || guess < 1)
{
System.out.println("Invalid input. Please re-enter a number"
+ " between 1 and " + MAX + ":");
guess = scan.nextInt();
}
if (guess == answer)
{
count++;
System.out.println("You guessed correctly!");
}
else if (guess > answer)
{
count++;
System.out.println("You guessed too high. Guess again? Y/N:");
another = scan.nextLine();
}
else if (guess < answer)
{
count++;
System.out.println("You guessed too low. Guess again? Y/N:");
another = scan.nextLine();
}
}
}
System.out.println("It took you " + count + "guess(es) to win.");
System.out.println("Do you wish to play again? Y/N:?");
another = scan.nextLine();
count = 0;
answer = generator.nextInt(MAX) + 1;
}
}
One problem is that you're not letting the user quit midway through the game because even if the user guesses a number within the 1 to 100 range and doesn't get the right answer, his or her answer to Guess again: Y/N: won't be checked since the current loop it is in only compares guess to answer, never another. Therefore, you'll end up being in an infinite loop in this case because if the user guesses 57 when the answer is 50, you'll just continuously prompt the user if he or she wants to guess again.
My recommendation would be to remove the second while loop
while (guess != answer)
{
//other stuff
}
and place the code inside that loop into the outside while loop
while(another.equalsIgnoreCase("y")){
//other stuff
}
And if you want the user to be able to play again, I would recommend putting this snippet of code you had earlier inside the if statement where you check if the user has guessed correctly,
if (guess == answer)
{
count++;
System.out.println("You guessed correctly!");
System.out.println("It took you " + count + "guess(es) to win.");
System.out.println("Do you wish to play again? Y/N:?");
another = scan.nextLine();
count = 0;
answer = generator.nextInt(MAX) + 1;
}
This way, if the user wins the game, their choice to play again will be checked in the while loop. One last thing I would recommend is moving this line
guess = scan.nextInt();
inside the while loop that checks another so that if the user wants to play again, the game will prompt the user for a guess.

Making a HiLo program~ having trouble getting the game to repeat [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
so, for my Java class I need to make a HiLo game. I figured the game out on my own, but I wanted to take it a step further, and after the user completes the game(guesses the right number) I want to ask them if they would like to play again.
The problem is, I can't seem to figure out exactly how. I have tried several things and at the moment I'm trying to get them to enter either yes or no to continue playing the game. If someone could help me figure out what I'm doing wrong and explain it to me, that would be great. Thanks!
Random generator = new Random();
Scanner scan = new Scanner(System.in);
int answer, guess;
answer = generator.nextInt(101);
System.out.println("Lets play a game. Guess the number(0-100): ");
guess = scan.nextInt();
while (guess != answer){
System.out.println("Wrong guess.");
if (guess > answer){
System.out.println("Your guess was higher than the answer. Guess again: ");
}
else{
System.out.println("Your guess was lower than the answer. Guess again: ");
}
guess = scan.nextInt();
}
if (guess == answer)
System.out.println("You got it! The number was " + answer);
//after initial game finishes, we ask if they want to play again.
System.out.print("Want to play again? ");
String again = scan.nextLine();
while (again != "no"){
System.out.println();
System.out.print("Great! lets play again.");
System.out.println("Take a guess(0-100 inclusive): ");
guess = scan.nextInt();
while (guess != answer){
System.out.println("Wrong guess.");
if (guess > answer){
System.out.println("Your guess was higher than the answer. Guess again: ");
}
else{
System.out.println("Your guess was lower than the answer. Guess again: ");
}
guess = scan.nextInt();
if (guess == answer)
System.out.println("Your got it! The number was " + answer);
System.out.println("Want to play again? (0 for no, 1 for yes): ");
again = scan.nextLine();
}
}
System.out.println("Thanks for playing!");
}
}
The != operator does not check if two strings contain the same characters. What you want to do is:
while (again.equals("yes")) {
...
}
You should also try to put your game code inside another loop, so at the end of the game (still inside the loop) you can ask the player if they want to play again. If yes, the loop has to be executed again, otherwise it stops.
This way the player can play an infinite number of games and you don't need to duplicate your game code. Example (to get an idea of what the structure could look like):
// start with "yes" in order to enter the game loop initially
String again = "yes";
while(again.equals("yes")) {
answer = generator.nextInt(101);
System.out.println("Lets play a game. Guess the number(0-100): ");
guess = scan.nextInt();
while (guess != answer){
System.out.println("Wrong guess.");
if (guess > answer){
System.out.println("Your guess was higher than the answer. Guess again: ");
}
else{
System.out.println("Your guess was lower than the answer. Guess again: ");
}
guess = scan.nextInt();
}
System.out.println("You got it! The number was " + answer);
// ask them if they want to play again. only "yes" will start another game
System.out.println("Do you want to play again (yes/no)?");
again = scan.nextLine();
}

Java Looping issue in Hangman program(Cant find)

I have the majority of my program finished, but now that I have most of the code it is tough to find the errors. I have multiple errors at the moment, but the main error I really need help with is that my program will loop the same guess over & over if it is correct. It is in an infinite loop, & I cannot find where it is. This has also brought to my attention that my program will go into negative guesses as it is supposed to end when it gets to 0. Some other errors that would be nice to get help with is 1) it shows a correct guess as an incorrect guess 2) it can only replace one letter in the secret word if there are multiple it will give me an error & end the program. & 3) if I enter 9 to quit, it does not quit.
Thanks in advance for any help. I can add code if needed ( I am only posting the main body ATM.)
public static final int DICTIONARY = 15000;
public static final int GUESSES = 8;
public static final int SECRETLENGTH = 20;
public static void main(String[] args) {
int usedSize = 0, randomWord, guesses = GUESSES;
String word, secretWord, guess, incorrectGuess, correctWord, playAgain;
char letter;
try
{
// Set up connection to the input file
Scanner hangmanDictionary = new Scanner(new FileReader("dictionary.txt"));
String [] dictionary = new String [DICTIONARY];
while (usedSize < DICTIONARY && hangmanDictionary.hasNextLine()) {
dictionary[usedSize] = hangmanDictionary.nextLine();
usedSize++;
}
kbd.nextLine();
clearScreen();
randomWord = pickRandom(DICTIONARY);
word = dictionary[randomWord];
secretWord = secret(word);
//comment out when done testing
System.out.println(word);
System.out.println("Here is the word to guess: " + secretWord);
System.out.println("Enter a letter to guess, or 9 to quit.");
guess = kbd.next();
do {
while (!guess.equals("9") || !(guess.equals(word) && guesses > 0)) {
letter = guess.charAt(0);
incorrectGuess = "";
incorrectGuess += letter;
if (word.indexOf(letter) < 0) {
guesses--;
System.out.println("Incorrect guesses: " + incorrectGuess);
System.out.println("Number of guesses left: " + guesses);
System.out.println("Enter a letter to guess, or 9 to quit.");
guess = kbd.next();
}
else {
//FINSH THIS
correctWord = correctWord(guess, word, secretWord, letter);
System.out.println(correctWord);
System.out.println("Incorrect guesses: " + incorrectGuess);
System.out.println("Number of guesses left: " + guesses);
System.out.println("Enter a letter to guess, or 9 to quit.");
guesses--;
}
}
if (guess.equals("9")) {
System.out.println("Thanks for playing!");
System.exit(0);
}
if (guess.equals(word)) {
System.out.println("You won!");
}
if (guesses == 0) {
System.out.println("You are out of guesses.");
}
System.out.println("Play again? Y/N");
playAgain = kbd.nextLine().toUpperCase();
} while (playAgain.equals("Y"));
}
catch (FileNotFoundException e) {
System.out.println("There was an error opening one of the files.");
}
}
Here's my guess:
Did you forget to put guess = kbd.next(); if the user guessed a correct character?
The inner while loop is your main problem, i.e. think about what happens when you enter a valid letter (guess), in that case the first condition of the while loop OR condition is TRUE (assuming you don't have a 9 in your secret word), so the while loop is entered without entering the second part of the OR condition. After that you enter the else part of the IF statement (since it's a valid guess) but in the else part you're not asking for the next guess, so it returns to the start of the while loop with the same guess and hence infinite loop.
Similarly, if you enter 9 to exit !guess.equals("9") evaluates to FALSE, so the second part of the OR condition is entered, in the second part
!(guess.equals(word) && guesses > 0) evaluates to TRUE (unless the secret word contains a 9) so you enter the WHILE loop which is invalid. etc ...
Try to write small parts of the code using known parameters and then bring it all together, that way it'll be easier to construct and follow the logic.

Will not stop looping

Write a program that generates a random number (between 1 and 10) and asks the user to guess what the number is. If the user’s guess is higher than the random number, the program should display “Too high, try again.” If the user’s guess is lower than the random number, the program should display “Too low, try again.” The program should use a loop that repeats until the user correctly guesses the random number.
This is my code and when I run it, it will not stop looping and I have no idea why. Thank you!!
/////guess/////
import java.util.Random;
import java.util.Scanner;
public class guess
{
public static void main (String [] args)
{
Random rand = new Random();
int numberToGuess =rand.nextInt(10);
Scanner input=new Scanner(System.in);
int guess;
boolean win =false;
while (win == false)
System.out.println("Guess a number between 1 and 10");
guess = input.nextInt();
{
if(guess == numberToGuess)
win=true;
}
if(guess<numberToGuess)
{
System.out.println("Your guess is too low");
}
{
if (guess > numberToGuess)
System.out.println("Your guess is too high");
System.out.println("You win!");
System.out.println("The number was" +numberToGuess);
}
}
}
This doesn't just apply to while statements; if and for statements are affected by this as well.
Your while statement will only ever execute the next line if it is not contained in a block.
// Without curly braces, the println is the only thing in the loop.
while (win == false)
System.out.println("Guess a number between 1 and 10");
// This isn't part of the loop!
guess = input.nextInt();
You fix this by ensuring that everything you want to loop on is contained by curly braces:
while(!win) {
// ALL of the logic you want to execute while win is false
}
Provided you have copied your code as is, have a look at your while loop you have no {} so it will keep printing
System.out.println("Guess a number between 1 and 10");
until win changes, which in this code it won't.

How can you check user input validation in Java?

I'm making a simple program that asks the user to input five numbers between 0-19. I would like to add something (like an if statement) after every number to make sure it's within that range. If not, the program should say "please read instructions again" and will then System.exit(0). This is the piece of the code that is relevant:
System.out.println("Please enter 5 numbers between 0 and 19");
System.out.print("1st Number: ");
userNum1 = scan.nextInt();
System.out.print("2nd Number: ");
userNum2 = scan.nextInt();
System.out.print("3rd Number: ");
userNum3 = scan.nextInt();
System.out.print("4th Number: ");
userNum4 = scan.nextInt();
System.out.print("5th Number: ");
userNum5 = scan.nextInt();
Any help would be greatly appreciated.
You can put this after each of your inputs, but you might want to think about putting this logic into its own method, then you can reuse the code and just call it with something like validateInput(userNum1);.
Replace val with your actual variable names.
if (val < 0 || val > 19) {
System.out.println("please read the instructions again");
System.exit(0);
}
First of all, I would create a for-loop that iterates N times, with N being the number of numbers you want to ask for (in your case, 5). Imagine your example with 50 numbers; it would be very repetitive.
Then, when you get each number with scan.nextInt() within your for-loop, you can validate however you want:
if (userNum < 0 || userNum > 19) {
// print error message, and quit here
}
Also, instead of just exiting when they input a number outside the range, you could have your logic inside a while loop so that it re-prompts them for the numbers. This way the user doesn't have to restart the application. Something like:
boolean runApplication = true;
while(runApplication) {
// do your for-loop with user input scanning
}
Then set the runApplication flag as needed based on whether or not the user put in valid numbers.
This code will do the trick for you, i added some securities :
public static void main(String[] args) {
int count = 1;
Scanner scan = new Scanner(System.in);
List<Integer> myNumbers = new ArrayList<Integer>();
System.out.println("Please enter 5 numbers between 0 and 19");
do {
System.out.println("Enter Number "+count+" ");
if(scan.hasNextInt()){
int input = scan.nextInt();
if(input >= 0 && input <= 19){
myNumbers.add(input);
count++;
}else{
System.out.println("Please read instructions again");
System.exit(0);
}
}else{
scan.nextLine();
System.out.println("Enter a valid Integer value");
}
}while(count < 6);
/* NUMBERS */
System.out.println("\n/** MY NUMBERS **/\n");
for (Integer myNumber : myNumbers) {
System.out.println(myNumber);
}
}
Hope it helps
Since you already know how many numbers you want the user to input, I suggest you use a for loop. It makes your code more elegant and you can add as many more entries as you want by changing the end condition of the loop. The only reason it looks long is because number 1, 2, 3 all end in a different format i.e firST secoND thiRD, but the rest of the numbers all end with TH. This is why I had to implement some if else statements inside the loop.
To explain the code, every time it loops it first tells the user the count of the number he/she is entering. Then numEntry is updated every time the loop loops, therefore you do not need to assign multiple inputs to multiple variables. It is more efficient to update the same variable as you go on. If the input the user inputs is less than 0 OR it is more than 19, the system exits after an error message.
System.out.println("Please enter a number between 0 and 19");
Scanner scan = new Scanner(System.in);
for(int i = 1; i <=5; i++){
if(i == 1)
System.out.println("1st Number");
else if(i == 2)
System.out.println("2nd Number");
else if(i == 3)
System.out.println("3rd Number");
else
System.out.println(i + "th Number");
int numEntry = scan.nextInt();
if(numEntry < 0 || numEntry > 19){
System.out.println("Please read instructions again.");
System.exit(1);
}

Categories

Resources