Hi guys,
I'm fairly new to Java, so please excuse my lack of knowledge on it :P
Anyway, I recently wrote a script; it didn't take me very long and it is far, far from complicated, but still, I'm just wondering whether if the code I've actually written is correct.
By that I mean, are the pragmatics of the code correct, is there a way to simplify it etc. It would be fantastic from my point of view if you could give me some feedback on it, as it'll greatly allow me to improve. I haven't commented it yet, but as it's not particularly complicated, I don't think that's necessary. Basically, it's a script where the computer guesses a number between 0 and 50, and you have 6 tries to try and guess it. If you don't succeed in guessing it within those 6 tries, then you lose, and vice versa. Also, the "TextIO.getln();" methods are from a foreign class, supplied by the book - it's basically a much superior scanner method.
Anyway, below is the code:
Code:
package TestWork;
public class GuessGame {
public static String id;
public static void main(String[] argv) {
System.out.println("Hello, it's time to play the guessing game!");
System.out.println("What's your name?");
id = TextIO.getlnString();
start();
}
public static void start() {
int userGuess, guessCount = 0, remain = 6, realNo, test;
realNo = (int)(50 * Math.random()) + 1;
System.out.println("Right, " + id + ", I will now guess a number between 1-50.");
System.out.println("If you get the right number within 6 tries, then you win!");
System.out.println("Otherwise, you lose! Ok " + id + ", let's begin!");
System.out.println();
System.out.println("Try and guess the number I'm thinking of! ");
while (true) {
userGuess = TextIO.getlnInt();
if (userGuess != realNo) {
guessCount++ ;
remain-- ;
System.out.println("Wrong! You have " + remain + " tries left.");
}
else if (userGuess == realNo) {
if (guessCount == 0) {
System.out.println("Unbelievable, you guessed my number in the first go! You are truly magnificent!");
System.out.println("Would you like to try again? Type '1' to restart or any other character to exit.");
test = TextIO.getlnInt();
if (test == 1) {
start();
}
else {
System.exit(0);
}
}
else if (guessCount != 0) {
System.out.println("Congratulations, you guessed my number, " + "'" + realNo + "' , in " + guessCount + " tries!");
System.out.println("Would you like to try again? Type '1' to restart or any other character to exit.");
test = TextIO.getlnInt();
if (test == 1) {
start();
}
else {
System.exit(0);
}
}
}
if (remain == 0) {
System.out.println("You're all out of guesses! You lose! ");
System.exit(0);
}
}
}
}
Thanks,
James