-2

我只是想知道是否有任何方法可以阻止用户输入负数或超过 4 位的数字。还有是否可以将此逻辑放入 GUI 中?这是我的代码:

import java.util.Scanner;
public class EasterSunday
{
    public static void main(String[] args)
    {
        int year; // declarations
        Scanner input = new Scanner(System.in); //start Scanner
        System.out.println("Enter in a year to find out the day and month of that Easter Sunday.");
        year = input.nextInt();
        int a = year%19;
        int b = year%4;
        int c = year%7;
        int d = (19 * a + 24) %30;
        int e = (2 * b + 4 * c + 6 * d + 5) %7;
        int eSunday = (22 + d + e);
        if ((year >= 1900) && (year <= 2099) && (year != 1954) && (year != 1981) && (year != 2049) && (year != 2076))
        {
            if (eSunday <= 30)
                System.out.println("Easter Sunday in " + year + " is March, " + eSunday);
            else
                System.out.println("Easter Sunday in " + year + " is April, " + (eSunday - 30));
        }
        else
        {
            if (eSunday <= 30)
                System.out.println("Easter Sunday in " + year + " is March, " + (eSunday - 7));
            else
                System.out.println("Easter Sunday in " + year + " is April, " + (eSunday - 37));
        }
    }
}
4

2 回答 2

0

您可以添加一个JFormattedTextField并将字符限制为最大长度为 4 的数字。这涵盖了负数,因为用户无法输入减号。

另一种解决方案是在简单的 JTextField 上使用InputVerifier 。

于 2012-06-17T18:47:43.450 回答
0

简单的答案是使用 while 循环,并且在用户输入符合您条件的数字之前不允许用户退出。

number = -1;
// while either the non-negativity or four-digit condition is not met
while(number < 0 || number > 9999){
    number = requestInput(user);
}

使用请求用户输入的函数 requestInput(user)。number = -1 的初始化是必要的,因为如果您只是声明它而不初始化它(如果内存服务),它将导致您的 IDE 抱怨它可能尚未初始化,或者程序将完全跳过 while 循环因为 0 在 (0, 9999) 范围内。

于 2012-06-17T19:22:11.453 回答