【问题标题】:How to fix variable not equaling user input如何修复变量不等于用户输入
【发布时间】:2020-04-24 04:11:27
【问题描述】:

我的程序要求用户输入一个数字,然后验证该数字是在两个随机生成的数字的范围内还是在该范围之外。变量 num 应该是用户的猜测,但它一直等于 0。我不确定它是否与 main 中的 num = 0 有关,因为我得到一个“变量可能未初始化”如果 = 0 不存在则错误。

代码:

public static int getValidGuess(Scanner get)
    {
       int num;

        System.out.print("Guess a number: --> ");
        num = get.nextInt();

        return num;
    } // getValidGuess end

    public static boolean displayGuessResults(int start, int end, int num)
    {

      boolean result;

    Random gen = new Random();

    int n1 = gen.nextInt(99) + 1;
    int n2 = gen.nextInt(99) + 1;


    if (n1 < n2){
        start = n1;
        end = n2;
    } //if end
    else
    {
        start = n2;
        end = n1;
    } //else end
    System.out.println("\nThe 2 random numbers are " + start + " and " + end);
    System.out.println("User Guess is " + num);
    if(num >= start && num <= end){
        result = true;
        System.out.println("Good Guess!");
    }
    else if(num < start || num > end){
        result = false;
        System.out.println("Outside Range.");
    }
    else{
        result = false;
    }
    return result;

    } // displayGuessResults end

    public static void main(String[] args) {
        // start code here
       int start = 0, end = 0, num = 0;
       Scanner scan = new Scanner(System.in);
       String doAgain = "Yes";

        while (doAgain.equalsIgnoreCase("YES")) {
            // call method
            getValidGuess(scan); 
            displayGuessResults(start, end, num);
            System.out.print("\nEnter YES to repeat --> ");
            doAgain = scan.next();
        } //end while loop

    } //main end

【问题讨论】:

    标签: java variables methods


    【解决方案1】:

    不同函数中的变量并不只是因为它们具有相同的名称而神奇地相同。如果您希望能够共享变量而不将它们作为参数或返回值传递,那么您需要在类中声明它们。

    具体来说,这是您的两个选择。选择 1(推荐):将 getValidGuess(scan); 更改为 num = getValidGuess(scan);。选择 2:将 public static int num = 0; 放在你的类中,放在你所有的函数之外,并从你的所有函数中删除 num 的声明。

    【讨论】:

    • 啊,有道理!虽然我对如何做有点困惑,有什么提示吗?
    • @Kaiju 不过,最好将它们作为参数传递。最佳实践是将数据项保持在尽可能小的范围内,因此“仅存在于此方法内的变量”比“存储在包含类中的变量”要好得多。特别是,当您的代码被多次调用时(例如在服务器中),您不希望多次执行相互中断。
    • 有效!太感谢了! @JosephSible-ReinstateMonica
    猜你喜欢
    • 1970-01-01
    • 2017-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 2019-12-19
    • 2019-12-02
    相关资源
    最近更新 更多