【问题标题】:How do I return a value inside the loop so that other methods can access it?如何在循环内返回一个值,以便其他方法可以访问它?
【发布时间】:2021-05-13 11:00:01
【问题描述】:

基本上,我需要返回正确的年份,即 2022 年以上。我需要返回它,以便其他方法可以访问它。如果用户不输入,这应该是一个循环提示错误。

        Scanner input = new Scanner(System.in);
        boolean good = false;
        do
        {
            System.out.println("Enter the expiration year:");
            int userYear = Integer.parseInt(input.nextLine());
            if(userYear > 2022)
              good = true;
            else 
              System.out.println("Invalid. Try again.");
            int userYears = Integer.parseInt(input.nextLine());
        }
        while (!good);
        good = false;

       // return userYear; 

我想回到这里,以便我的其他方法可以看到。

【问题讨论】:

    标签: java eclipse loops return do-while


    【解决方案1】:

    在循环之外创建 int userYears。然后只需更改循环内的值。您不需要 userYears 和 userYear。它们是变量,它们的值可以改变

    【讨论】:

    • 我很困惑这会有什么帮助,因为即使我更改了变量,它也不允许我返回我需要的输入值,以便其他方法可以访问它。
    • 您只需将该值传递给您需要的方法。或者你可以创建一个公共实例变量
    【解决方案2】:

    您可以立即退货

    if (userYear > 2022) {
        return userYear;
    }
    

    或者,如果您需要在返回值之前做一些事情,请在循环外部(之前)创建变量 userYear

    int userYear;
    do {
        // some code
    } while (!good);
    // some more code
    return userYear;
    

    【讨论】:

      猜你喜欢
      • 2013-11-06
      • 2013-06-04
      • 1970-01-01
      • 2023-03-30
      • 2015-08-30
      • 2021-10-22
      • 1970-01-01
      • 2012-11-01
      • 2018-08-28
      相关资源
      最近更新 更多