Hey all,
I'm still very much in learning mode here, so please help me out. The following code works fine, but I'm wondering if my if statements aren't a bit hoakey? This is the first application I wrote without looking at the book (too much). Please let me know what I could do to improve this (please bare in mind I'm still very new so keep it simple).
Thanks,
- MT
I'm still very much in learning mode here, so please help me out. The following code works fine, but I'm wondering if my if statements aren't a bit hoakey? This is the first application I wrote without looking at the book (too much). Please let me know what I could do to improve this (please bare in mind I'm still very new so keep it simple).
Thanks,
- MT
Code:
// RandomNumber.java
// Guess a random number between 1 and 100 within 20 guesses
import java.util.Random;
public class RandomNumber {
private int maxNumber;
private int totalGuesses;
private int x;
public RandomNumber() {
maxNumber = 100;
Random rand = new Random();
x = rand.nextInt(maxNumber+1);
}
public void takeAGuess(int guessedNumber, int count) {
if((guessedNumber < x) && (guessedNumber != x)) {
System.out.println("Oooh... so close, you'll need to guess higher than that.\n");
}
if((guessedNumber > x) && (guessedNumber != x)) {
System.out.println("Yeah, about that... um, can we try a little lower?\n");
}
if(guessedNumber == x) {
totalGuesses = 20 - count;
System.out.println("Dude, you guessed it and in only " + totalGuesses + " tries!");
}
}
public int getRN() {
return x;
}
}
Code:
// RunRNGame.java
// Runs RandomNumberGame.java program
import java.util.Scanner;
public class RNGame {
public static void main(String args[]) {
RandomNumber newGame = new RandomNumber();
int guessCount;
int userGuess;
int targetNumber;
System.out.println("Welcome to the Random Number Game!");
targetNumber = newGame.getRN();
guessCount = 20;
Scanner input = new Scanner(System.in);
userGuess = 0;
while ((guessCount > 0) && (userGuess != targetNumber)) {
System.out.println("You currently have " + guessCount + " chances left.");
System.out.print("What is your guess? ");
userGuess = input.nextInt();
newGame.takeAGuess(userGuess, guessCount);
--guessCount;
}
}
}