I need to make a program to illustrate the Random Class and loop sentinels. So far, I can ask for the input of the number. After that, there are countless logical issues that are coming up. Can anyone help me sort this out?

import java.util.Scanner;

import java.util.Random;

public class HiLo
{
	public static void main (String[] args)
	{
		Scanner keyboard = new Scanner (System.in);
		Random randomNumbers = new Random();

		int randomnumber, guess = 0, times = 0;
		char replayresponse;
		String input;
		randomnumber = randomNumbers.nextInt(100);

		System.out.println("Welcome to the game of Hi-Lo - A number guessing game");
		System.out.print("Enter your guess or -1 to quit: ");
		guess = keyboard.nextInt();



		while(guess != -1)
		{

			if(guess != randomnumber)
			{
				if (guess > randomnumber)
				{
					System.out.print("Hi!");
					times++;
				}
				else if (guess < randomnumber)
				{
					System.out.print("Low!");
					times++;
				}
			}
			else if (guess == randomnumber)
			{
				System.out.println("That's the number!");
				System.out.println("You took" + times + "guesses!");
				System.out.print("Want to play again? (Y/N): ");

				input = keyboard.nextLine();
				replayresponse = input.charAt(0);

				if (replayresponse == 'n')
				{
					System.out.print("Good bye!");
				}
				else if (replayresponse == 'y')
				{
					System.out.print("Guess another number between 1 and 100!: ");
					Random gen = new Random();
					randomnumber = gen.nextInt(100)+1;
					times = 1;
				}
			}
		if (guess == -1)
		System.out.println("You quit!\n You took " + times + " guesses!");
		System.out.println("Want to play again? (Y/N): ");

			input = keyboard.nextLine();
			replayresponse = input.charAt(0);

			if (replayresponse == 'n')
			{
				System.out.print("Good bye!");
			}
			if (replayresponse == 'y')
			{
				System.out.print("Guess a number between 1 and 100 or -1 to quit!: ");
				Random gen = new Random();
				randomnumber = gen.nextInt(100)+1;
				times = 1;
				}
		}
	}
}

I think you need to change your entire logic, as you may have already realized.

Your code should be something like this - you can put a do-while loop around the whole thing if you want to repeat:

do{
<take input, check if it is high, low, or equal to number>

if(<high>)
print out message
else if(<low>)
print out message

}while(guess!=number); 

<print out message displaying that user has won>
<end the game>

The problem with your current code is that you don't repeatedly get input from the user.

Edited 6 Years Ago by coil: n/a

This article has been dead for over six months. Start a new discussion instead.