简体   繁体   English

无法通过验证在JAVA中使随机数游戏正常工作

[英]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 isValid = 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.

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 have several small errors in your program: 您的程序中有几个小错误:

  • In the line before the "Too low!" 在行之前"Too low!" guessing message, you used the wrong comparison operator. 猜测消息,您使用了错误的比较运算符。
  • In the getIntWithinRange method you should allow min and max to be valid. getIntWithinRange方法中,应允许minmax有效。
  • 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 . 有一条评论告诉我们有关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. 一旦用户猜对了,就不应要求他再次猜测。

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. 您需要为验证创建单独的函数,并且可能要在输入上使用Integer.parseInt(String s)。 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 Integer.parseInt的文档: http : //download.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#parseInt%28java.lang.String%29

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM