2012-06-17 100 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)範圍內。

相關問題