2012-06-17 143 views
-2

我只想知道是否有任何方法阻止用户输入负数或4位以上的数字。反正也有把这个逻辑放到一个GUI中的吗?这里是我的代码:如何防止输入负数或4位以上的数字

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)); 
     } 
    } 
} 
+0

你应该问一个问题,并缩小代码? –

+0

对不起,这个我知道下次:) – FluX

回答

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)范围内。

相关问题