Help?? Guess number game

• 10-27-2013, 12:48 PM
eob13
Help?? Guess number game
Hi,

I'm new to java, have been learning for 4 weeks. Ive an assignment tomorrow and have been given the following clues which the exam will contain; comments, user input, constants, if else statement (more than 2), loop (only break if you get the value you want), wrong (please enter correct number), correct (do you want to play again).

I could be wrong but going by the above i think it could be a guessing game? I have got the following, but it needs to be changed to contain loops / constants etc. If anyone could help would be greatly appreciated, thanks in advance :

import java.util.Random;
import java.util.Scanner;

/**
* @author endaobrien1313
*
*/
public class HighLowGuess {

/**
* @param args
*/
public static void main(String[] args) {

//Get scanner
Scanner scanner = new Scanner (System.in);
Random generator = new Random ();

// Declaring variables
int num2;
int guessCount;
boolean playAgain = true;

while (playAgain) {
guessCount = 0;
int num1 = generator.nextInt(101) + 1;
// Tell user to guess a number
System.out.println("Guess a number between 1 and 100. \nEnter your guess (0 to quit): ");
// Get users input
num2 = scanner.nextInt();
scanner.nextLine();

//Check if
while (num2 != 0) {
if (num2 < num1) {
System.out.println("You guess was too low. \nGuess again (0 to quit): ");
num2 = scanner.nextInt();
scanner.nextLine();
guessCount++;
}
else if (num2 > num1) {
System.out.println("Your guess was too high. \nGuess again (0 to quit): ");
num2 = scanner.nextInt();
scanner.nextLine();
guessCount++;
}
else {
guessCount++;
System.out.println("Number of guesses: " + guessCount);
num2 = 0;
}
}
System.out.println("Would you like to play again? (y/n): ");
String input = scanner.nextLine();
if (input.equalsIgnoreCase("n")) {
playAgain = false;

}
}
scanner.close();

}

}
• 10-27-2013, 02:03 PM
Norm
Re: Help?? Guess number game