2012-06-17 3 views
-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)); 
     } 
    } 
} 
+0

하나의 질문을하고 코드를 좁혀 야합니까? –

+0

죄송합니다. 다음에 알 수 있습니다. :) – FluX

답변

0

당신은 사용자가 마이너스 문자를 입력 할 수 없기 때문에이 음수를 포함 4의 최대 길이 번호로 문자를 JFormattedTextField를 추가하고 제한 할 수 있습니다 : 여기 내 코드입니다.

다른 해결책은 간단한 JTextField에서 InputVerifier을 사용하는 것입니다.

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) 함수를 사용합니다. 초기화하지 않고 (메모리가 제공되는 경우) 단순히 선언하면 IDE에서 초기화되지 않았다고 불평하거나 프로그램이 while 루프를 건너 뛸 수 있기 때문에 number = -1의 초기화가 필요합니다. 0은 (0, 9999) 범위에 있기 때문입니다.

관련 문제