2014-11-22 1 views
0

학교에서 몇 가지 기능이있는 간단한 시계를 만들도록 요청을 받았습니다.자바 - 내 생성자에 대한 입력 제한 만들기

나는 사람들이 좋은 정수를 입력 할 수 있도록 개체를 만들 수 있도록 몇 가지 종류의 제약이 필요합니다. 예를 들어; 당신은 시간에 25를 입력하거나 분과 초에 60을 초과하는 정수를 입력 할 수 없습니다.

시간, 분 및 초에 대한 인스턴스 변수를 만들기 시작했습니다. 나는 생성자를 만들었다.

내 코드는 다음과 같습니다 :

public class Clock{ 

    //Instance variables 
    public int seconds; 
    public int minutes; 
    public int hours; 

public Clock (int InsertSeconds, int InsertMinutes, int InsertHours){ 
    seconds = InsertSeconds; 
    minutes = InsertMinutes; 
    hours = InsertHours; 
} 

} 

시; 나는 자바에서 초보자이다. 나에게 총을 발사하지 말아라.

고마워!

+0

날짜 및 시간 라이브러리를 사용할 수있는 경우 - Apache의 TimeValidator - http://commons.apache.org/proper/commons-validator/apidocs/org/apache/commons/validator/routines/TimeValidator를 사용해보십시오. htaccess Admin Home English Language Content – ha9u63ar

+0

에 오신 것을 환영합니다 Stackoverflow. 처음 시도한 것을 보여주는 것이 좋은 습관입니다. 그에 따라 질문을 편집하십시오. 힌트 : 입력 된 값이 유효한지 확인하고 그렇지 않은 경우 예외를 throw 할 수 있습니다. –

+0

자바 기본 연산자 (http://www.tutorialspoint.com/java/java_basic_operators.htm), 의사 결정 (http://www.tutorialspoint.com/java/java_decision_making.htm) 및 예외 (http : //www.tutorialspoint.com/java/java_exceptions.htm) 정확한 질문으로 다시 돌아옵니다. – Kraal

답변

0

예외를 발생시킵니다. IllegalArgumentException은 좋은 선택 일 것입니다.

public Clock (int InsertSeconds, int InsertMinutes, int InsertHours){ 
    if (InsertSeconds > 59 || InsertSeconds < 0) { 
     throw new IllegalArgumentException("InsertSeconds must be in range 0-59 but found "+ InsertSeconds); 
    } 
    // similar for minutes & hours 

    seconds = InsertSeconds; 
    minutes = InsertMinutes; 
    hours = InsertHours; 
} 
+0

off-by-1로 수정 됨 –

0

예외를 사용하십시오! 예를 들어 :

if(seconds > 60) 
    throw new SecondsTooBigException(); 

그리고 당신은해야합니다, 당신은 기본 흐름 제어를 사용할 수있는 시계가 (즉, 간단한 솔루션) 24 시간 형식이 가정 새로운 SecondsTooBigExcetion

public class SecondsTooBigException extends Exception { 
    @Override 
    public String getMessage() { 
     return super.getMessage() + "\nSecondsTooBigException: Exception occured, because you defined a value, which is not allowed for seconds"; 
    } 
} 
+0

필요한 경우 다른 방법도 무시할 수 있습니다. – Nikolar

+0

감사합니다! 정말 필요합니다 –

0

을 만들 수 있습니다 :

public boolean areAllSegmentsValid() { 
    if (this.hours < 0 || this.hours > 24) { 
     System.out.println("Hours are not in range 0-24"); 
     // A better of option wil be exception (you are novice so learn about first) 
     return false; 
    } else if (this.minutes < 0 || this.minutes > 60){ 
     System.out.println("Minutes are not in range 0-24"); 
     // A better of option wil be exception (you are novice so learn about first) 
    } else if (this.seconds < 0 || this.seconds > 60){ 
     System.out.println("Minutes are not in range 0-24"); 
     // A better of option wil be exception (you are novice so learn about first) 
    } else { 
     return true; 
    } 

    return true; 
} 

위의 해결 방법을 사용하려면 원래 질문에서 이미 지적한 Java에 대한 최소한의 이해가 필요합니다. 이 개념을 파악하면, 나는 당신이 시도하고 대체하는 주장을 사용 제언

assert (this.hours >= 0 && this.hours<=24); // Assertion to check if the cond. is true 
... 
... 

더 많은 자바 방법 : 예 : 위의 조건은 예를 들어, 당신의 시계 클래스에 대한 예외를 사용하는 경우 IllegalHoursValue 예외 또는 IllegalTimeSegment 예외입니다. 그러나 나머지는 안전하게 조사해 드리겠습니다.

0

는이 정적 메소드를 사용할 수 있습니다

public static boolean validTime(int hours, int minutes, int seconds) { 
    if (hours <= 24 && minutes <= 60 && seconds <= 60) { 
     if (hours >= 0 && minutes >= 0 && seconds >= 0) { 
      return true; 
     } 
    } 
    return false; 
} 

는 그런 사용자 입력 값을 지정합니다. true을 반환하면 생성자로 전달하고, 그렇지 않으면 값을 다시 입력하라는 메시지가 사용자에게 표시됩니다.

+0

내 임무를 계속 수행하는 동안 나중에 다른 옵션을 구현할 것을 요청하기 때문에 새로운 IllegalArgumentException을 throw하는 것이 쓸모가 없다는 것을 알았습니다. tot 값이 60을 초과하여 초과 할 수 있도록 값을 사용하여 초 또는 분을 늘리면 1을 사용하여 tot 값이 다른 값을 증가시켜야합니다. ie 다음 시간은 10:12:59이고 그 시간은 1 초 결과는 10:13:00이어야합니다. –

+0

그건 별개의 문제인 것처럼 보입니다. 새로운 질문을하고 누군가가 당신을 도울 수 있는지 알아볼 것을 권합니다. –

관련 문제