有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用while循环来不断请求用户输入

我已经尝试了两种使用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");
    }
}

共 (3) 个答案

  1. # 1 楼答案

    您应该将输入代码放入while循环中,并在while循环中执行,直到年份为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");
            }
    
    
        }
    
  2. # 2 楼答案

    在输入线上使用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");
        }
    }
    
    }
    
  3. # 3 楼答案

    您需要做一些事情来保持输入循环运行,直到遇到停止条件(在您的情况下,就是当用户输入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