Ok, I am making a hi_lo game where the computer generates a random number, which you have to guess, everytime you guess it tells you if you are low or higher than the number. Once you reach it, it tells you how many guesses it took and if you want to play again. I have a while loop to go back to it, I cant get it to work.
Here is my code.
CODE
import java.util.Scanner;
public class hi_lo
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int answer, guess = 1455486, count=1, yn=1;
answer = (int)(Math.random() * 100 + 1);
System.out.println ("Guess a number between 1 and 100, 0 to quit");
guess = scan.nextInt();
{
while (yn == 1)
{
while (guess != 0 && guess != answer)
{
count++;
if (guess < answer)
System.out.println ("Your to low, guess again or zero to quit ");
else
System.out.println ("Your to high, guess again or zero to quit ");
guess = scan.nextInt();
}
if (guess == answer)
{
System.out.println ("You guessed it right! It took you " + count++ + " guesses! Do you want to play again? 1 for yes, 0 for no");
}
yn = scan.nextInt();
}
}
}
}
Another way to look at it.
CODE
import java.util.Scanner;
public class hi_lo
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int answer, guess = 1455486, count=1, yn=1;
answer = (int)(Math.random() * 100 + 1);
System.out.println ("Guess a number between 1 and 100, 0 to quit");
guess = scan.nextInt();
{
while (yn == 1)
{
while (guess != 0 && guess != answer)
{
count++;
if (guess < answer)
System.out.println ("Your to low, guess again or zero to quit ");
else
System.out.println ("Your to high, guess again or zero to quit ");
guess = scan.nextInt();
}
if (guess == answer)
{
System.out.println ("You guessed it right! It took you " + count++ + " guesses!");
}
System.out.println ("Do you want to play again? 1 for yes, 0 for no.");
yn = scan.nextInt();
}
}
}
}