Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/371.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/eclipse/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在循环中返回一个值,以便其他方法可以访问它?_Java_Eclipse_Loops_Return_Do While - Fatal编程技术网

Java 如何在循环中返回一个值,以便其他方法可以访问它?

Java 如何在循环中返回一个值,以便其他方法可以访问它?,java,eclipse,loops,return,do-while,Java,Eclipse,Loops,Return,Do While,基本上,我需要返回正确的年份,即2022年以上。我需要返回它,以便其他方法可以访问它。假设这是一个循环,如果用户没有键入它,它会说error Scanner input = new Scanner(System.in); boolean good = false; do { System.out.println("Enter the expiration year:");

基本上,我需要返回正确的年份,即2022年以上。我需要返回它,以便其他方法可以访问它。假设这是一个循环,如果用户没有键入它,它会说error

        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; 

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

在循环之外创建int userYears。然后简单地更改循环中的值。您不需要同时使用userYear和userYear。它们是变量,其值可以更改

您可以立即返回它

if (userYear > 2022) {
    return userYear;
}
或者,如果在返回值之前需要执行一些操作,请在循环外部(之前)创建变量
userYear


我不知道这会有什么帮助,因为即使我更改变量,它也不允许我返回所需的输入值,以便其他方法可以访问它。您只需将该值传递到所需的方法中。也可以创建公共实例变量
int userYear;
do {
    // some code
} while (!good);
// some more code
return userYear;