2014-03-05 2 views
-1

문자열을 확인하기 위해 사용자 정의 예외를 만들려면 어떻게해야합니까? = 1? 지금까지 이것이 내가 가지고있는 것이지만, 그것이 옳다는 것이 거의 확실한 것인지 잘 모르겠습니다. 그래서, 그에 대한 예외를 가지고 싶습니다 자바에서 문자열에 대한 사용자 정의 예외

나는 카드 게임을 프로그래밍하기 위해 노력하고있어, 나는

if (rank.length() != 1) { 
     return; 
    } 

에 대한 예외를 throw합니다. 여기

public class StringLengthException extends Exception{ 


    public StringLengthException() {} 


    public StringLengthException (String message) 
    { 
    super(message); 
    } 

} 

내가 문자열의 길이가 1에 동일한 경우는, 예외를 던져 그렇다면,

/** 
* Name mutator. 
* 
* Business rules: - should be in the range A, 1, ..., 9, T, J, Q, K 
* 
* @param rank the rank to set 
*/ 
public void setRank(String rank) { 
    // make sure the rank isn't null 
    if (rank == null) { 
     throw new NullPointerException ("Rank is null"); 
    } 
    // make sure the rank isn't too long or too short 
    if (rank.length() != 1) { 
     return; 
    } 
    rank = rank.toUpperCase(); 
    // check if the rank is one of the allowed ones 
    if ("A23456789TJQK".contains(rank)) { 
     this.rank = rank; 
     // is this an ace? 
     if (rank.equals(ACE)) { 
      this.value = 1; 
     } else // perhaps it is a face card? 
     if ((TEN + JACK + QUEEN + KING).contains(rank)) { 
      this.value = 10; 
     } else { 
      // it must be a regular card 
      this.value = Integer.parseInt(rank); 
     } 
    } 
} 
+0

당신은'IllegalArgumentException'을 찾고 계십니까? –

+0

위의 편집을 확인하십시오. – user3382217

답변

1

의 예외 당신이 할 수있는 것은 확인하는 것입니다를 작성하는 노력하고있어 클래스의 :

String str = "..."; 

if (str.length() == 1) 
    throw new StringLengthException(); 

당신은 방법 안에,이를 추가해야한다

public void someOperationWithStrings(String str) throws StringLengthException { 
    if (str.length() == 1) 
     throw new StringLengthException(); 
} 

메서드 내에 예외가 발생하면 메서드가 예외을 throw한다고 선언해야한다는 것을 잊지 마십시오.

0

예외 상황은 예외적 인 상황이 발생할 경우 정보와 함께 표시됩니다. 일부 작업이 진행되는 동안 예외적 인 상황을 파악해야합니다.

if (yourstring.length != 1){ 
    throw new StringLengthException(); 
    } 

은 또한 예외가 메시지를 포함해야합니다, 그래서 원인의 식별이 쉬워집니다 : 귀하의 경우와 마찬가지로, 문자열 길이 같지 1. 그래서 코드처럼 보일 것입니다.

if (yourstring.length != 1){ 
    throw new StringLengthException("String length is not equal to 1: String is:" + yourstring); 
    } 
0

클래스는 좋다, 당신이 지금해야 할 유일한 것은 그것을 사용할 수 있습니다 : 당신이 원하는 경우,

try { 
    String rank = "A"; 
    doSomething(rank); 
} catch (StringLengthException sle) { 
    sle.printStackTrace(); 
} 

:하지만, 그런 방법을

public void doSomething (String rank) throws StringLengthException { 
    if (rank.length()!=1) 
     throw new StringLengthException("rank is not of size 1"); 

    // Do stuff 
} 

을 그리고 전화 문자 만 저장하려면 Character 또는 char 유형을 사용하지 않으시겠습니까?