簡體   English   中英

如何在 while 循環內返回用戶輸入值?

[英]How do I return the user input value inside of a while loop?

我想返回 userYear,或者換句話說,用戶給我的輸入。 它告訴我在循環外初始化變量。 當我這樣做時,它告訴我變量是重復的。 我想做的只是返回輸入,以便我的其他程序方法可以使用它們。

public static int readTheYear() {
    
    Scanner scan = new Scanner(System.in);
    boolean correctYear = false;
    do
    {
        System.out.println("Enter theyear:");
        int userYear = Integer.parseInt(scan.nextLine());
        if(userYear > 2025)
        correctYear = true;
        
        else 
        System.out.println("Invalid. Try again.");
        
    }
    while (!correctYear);

    correctYear = false;
    return userYear; // gives an error
    
}

基本思想:

int userYear;
...
do {
    ...
    userYear = ...  // no 'int' here!!
    ...
} while (...);
...
return userYear;

注1:不需要if ,只需要correctYear = userYear > 2025;

注2:根本不需要正確的correctYear

int userYear;
...
do {
    ...
    userYear = ...
    // no if here
    ...
} while (userYear <= 2025);
...
return userYear;

替代方案,正如喬恩所建議的那樣:

...
while(true) {
    ...
    int useYear = ...
    if (...) {
        return useYear;
    }
    ...
}

您需要做的是在 while 循環之外聲明變量“userYear”。 那是因為while循環有它自己的scope,並且在其中聲明的變量只在這個循環中有效。 在 Java 中閱讀有關 scope 的更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM