簡體   English   中英

我將如何使用while循環來不斷請求用戶輸入

[英]How would I use a while loop to keep requesting user input

我用while循環嘗試了幾件事,但似乎無法使其正常工作。 我想一直請求用戶輸入,直到用戶輸入數字0,這是我到目前為止的代碼:

import java.util.*;

public class Task10 {

    public static void main(String[] args) {
        System.out.println("Enter a year to check if it is a leap year");
        Scanner input = new Scanner(System.in);
        int year = input.nextInt();

        if ((year % 4 == 0) || ((year % 400 == 0) && (year % 100 != 0)))
            System.out.println(year + " is a leap year");
        else
            System.out.println(year + " is not a leap year");
    }
}

在輸入行上方使用while循環作為:

 while(true)

並且,使用if條件break

if(year == 0)
    break;

另外, leap year條件在您的代碼中是錯誤的。 它應該是:

if((year % 100 == 0 && year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
    //its a leap year
else
    //its not

PS:在評論中,我將提供完整的代碼:

import java.util.*;

public class Task10 {

public static void main(String[] args) {
    System.out.println("Enter a year to check if it is a leap year");
    while(true){
    Scanner input = new Scanner(System.in);
        int year = input.nextInt();
        if(year == 0)
            break;
        if((year % 100 == 0 && year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
            System.out.println(year + " is a leap year");
        else
            System.out.println(year + " is not a leap year");
    }
}

}

您應該將輸入代碼放入一個while循環和執行while循環中,直到year等於或小於0。

public static void main(String[] args) {
        int year = 1;
        while(year > 0)
        {
            System.out.println("Enter a year to check if it is a leap year");
            Scanner input = new Scanner(System.in);
            year = input.nextInt();
            if ((year % 4 == 0) || ((year % 400 == 0) && (year % 100 != 0)))
                System.out.println(year + " is a leap year");
            else
                System.out.println(year + " is not a leap year");
        }


    }

您需要做一些事情來保持輸入循環運行,直到遇到停止條件為止(在您的情況下,這是用戶輸入0

// First get the scanner object with the input stream
Scanner sc = new Scanner(System.in); 

// Just using do-while here for no reason, you can use a simple while(true) as well
do{
    int input = sc.nextInt();  // read the next input
    if (int == 0) { // check if we need to exit out
        // break only if 0 is entered, this means we don't want to run the loop anymore
        break;
    } else {
        // otherwise, do something with the input
    }
} while(true); // and keep repeating

暫無
暫無

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

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