本文介绍了我将如何使用 while 循环来不断请求用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经用 while 循环尝试了一些东西,但似乎无法让它工作.我想一直请求用户输入,直到用户输入数字 0,这是我到目前为止的代码:

I've tried a couple of things with the while loop and can't seem to get it to work. I want to keep requesting user input until the user inputs the number 0, here is the code I have so far:

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 循环:

Use a while loop above input line as:

 while(true)

并且,使用if条件来break.

if(year == 0)
    break;

此外,您的代码中 leap year 的条件是错误的.应该是:

Also, condition for leap year is wrong in your code. It should be:

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

PS:和评论一样,我会给出完整的代码:

PS: As in comments, I'll give a complete code:

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 循环来不断请求用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 16:41