如何制定自定義異常以確定字符串!= 1? 到目前爲止,這是我的,但我不確定它是否接近正確。Java中的字符串自定義異常
我想編寫一個紙牌遊戲,我想拋出一個例外
if (rank.length() != 1) {
return;
}
所以,我想有該例外。
public class StringLengthException extends Exception{
public StringLengthException() {}
public StringLengthException (String message)
{
super(message);
}
}
這裏是我嘗試寫
/**
* 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);
}
}
}
你在找'IllegalArgumentException'嗎? –
檢查上面的編輯 – user3382217