开发者

Can't Make a Random Number Game Work in JAVA With Validations

I hope it's permissible here to post large chucks of code, but I'm having no luck with an assignment. We have to create a game were the computer generates a random number and the user has seven chances to guess it. The problem is that we have to validate every user input and that is, I think, where I'm falling apart. Our instructor has firmly stated that the validation for whether the user enters and integer and whether that integer is withing the range specified are to be in separate methods. I've botched the thing but since I'm not even sure WHERE the errors are I'm posting it all here. I hope that's not against any rules.

import java.util.*;

public class RandomNumber {

   public static void main(String[] args) {

    // Welcome user to program
    System.out.println("Welcome to the Random Number Game!\n");

    // Create Scanner Object
    Scanner sc = new Scanner(System.in);
    String choice = "y";
    while (choice.equalsIgnoreCase("y")) {

        // Get Random Double Number
        double randNumber = Math.random();
        double d = randNumber * 100;
        int randomNum = (int)d + 1;

        // Beginning Game Message
        System.out.println("I'm thinking of a number between 1 - 100.");
        System.out.println("Can you guess it?");

        // Obtain User Guesses
            for(int i = 1; i <= 7; i++) {
                System.out.println("Let''s Play!\n");
                int userInt = getIntWithinRange(sc, "Enter your guess: ", 1, 100);

                if (userInt >= randomNum + 10) 
                    System.out.println("Way too high!");

                else if (userInt > randomNum)
                    System.out.println("Too high!");

                else if (userInt > randomNum)
                    System.out.println("Too low!");

                else
                    System.out.println("You guessed right!");
        } // End For Loop


    // See if user wants to play again          
choice = "x";
while (!choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n")) {
        System.out.println("Do ou wish to play again? (y/n): ");
        choice = sc.next();
        sc.nextLine();

            if (!choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n")) {
                System.out.println("Error! Not a valid responce!");
            } // End if Loop.

        } // End While Choice Loop.

    } // End While Loop.

    } // End Main.


    public static int getIntWithinRange(Scanner sc, String prompt, int min, int max) {
    int number = 0;
        boolean isVali开发者_如何学运维d = false;
        while (isValid == false) {
            number = getInt(sc, prompt);
            if (number <= min)
                System.out.println("Error! Number must be greater than " + min + ".");
            else if (number >= max)
                System.out.println("Error! Number must be greater than " + max + ".");
            else
                isValid = true;

        }// End While Loop
        return number;

    } // End Rage Checker


    public static int getInt (Scanner sc, String prompt) {
        int number = 0;
        boolean isValid = false;
        while (isValid == false) {
            System.out.print(prompt);

            if (sc.hasNextInt()) {
                number = sc.nextInt();
                isValid = true;
            } // End If

            else {
                System.out.println("Error! Invalid integer value.  Try again.");
            } // End Else

            sc.nextLine();      
        } // End While Loop
        return number;

    }// End Integer Checker

} // End Class.


You have several small errors in your program:

  • In the line before the "Too low!" guessing message, you used the wrong comparison operator.
  • In the getIntWithinRange method you should allow min and max to be valid.
  • In the same method you should print the appropriate error message when the number is too large.
  • One comment tells us about an If Loop. It's not a loop, it's just a conditional statement.
  • As soon as the user guessed right, he shouldn't be asked to guess again.


Making this change makes it work right for me.

System.out.println("Let's Play!\n");//Moved outside for loop
// Obtain User Guesses
int userInt=0;//declaration moved outside for loop
for(int i = 1; i <= 7; i++) {
    userInt = getIntWithinRange(sc, "Enter your guess: ", 1, 100);
    if (userInt >= randomNum + 10) 
        System.out.println("Way too high!");
    else if (userInt > randomNum)
        System.out.println("Too high!");
    else if (userInt < randomNum)//Changed to < otherwise if userInt<=randomNum, you win.
        System.out.println("Too low!");
    else{
         System.out.println("You guessed right!");
         break;//exit loop once user guesses right
    }
} // End For Loop
if(userInt!=randomNum)
    System.out.println("You lose"); //Print loss.

Amount of code is fine, helpful even, because we can test the program ourselves. Also changed:

else if (number >= max)
    System.out.println("Error! Number must be less than " + max + ".");


You need to change the wording for your validation where the number is too big.

Enter your guess: 101
Error! Number must be greater than 100.

You would need to make separate functions for the validation, and you might want to use Integer.parseInt(String s) on the input. Since it's an assignment I'm not going to tell you exactly how to do it.

Documentation for Integer.parseInt: http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#parseInt%28java.lang.String%29

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜