What's wrong with my code?
Two questions, why doesn't my program let me keep putting in numbers until I guess the right one?
What is wrong with my loop? Pressing 1 should repeat the program, any other number should close.
Thanks!
Quote:
import java.util.Random;
import java.util.Scanner;
public class HighLowGame
{
public static void main(String[] args)
{
Random rand = new Random();
int numberOfTries = 0;
Scanner input = new Scanner(System.in);
char repeat;
char ans;
int guess;
boolean win = false;
do {
System.out.println("Pick a number between 0 and 10: ");
guess = input.nextInt();
numberOfTries++;
int numberToGuess = rand.nextInt(10);
if (guess == numberToGuess) {
win = true;
System.out.println("Congratulations you have won!");
}
else if (guess > numberToGuess) {
System.out.println("Your guess was high try again");
}
else if (guess < numberToGuess) {
System.out.println("Your guess was low try again");
}
System.out.println("The number was " + numberToGuess);
System.out.println("You guessed the number in "+ numberOfTries + " attempt(s)");
System.out.println("New game? 1 for Yes, or any other number to quit ");
ans = input.next().charAt(0);
} while (ans == 1);
}
}
Re: What's wrong with my code?
One problem I notice right away is that if they guess incorrectly it will tell them if they are too low or high, and then give them the answer and ask if they want to try again. if you enter 1 your program will allow you to input more numbers, if you enter something else it won't since it doen't meet the condition.
Try using a do while to set up the number, and then have a while loop inside the do to ask for an input and test it. It should keep looping indefinitely. If they guess the correct number it should let them know, tell them the amount of attempts it took, and break out of the loop, then it should ask them if they want to continue.
Code java:
do
set random num
while(condition)
if(condition)
print info and break
print info and ask if they want to continue
while(condtion)