Lecture 12 - CS 159 Exceptions + Enums
Prof. Alvin Chao
Due this week:
Exceptions Activity
Exceptions
Consider the card class:�public Card(int rank, int suit) {
if (rank < 1 || rank > 13) {
throw new IllegalArgumentException(
"invalid rank: " + rank);
}
if (suit < 0 || suit > 3) {
throw new IllegalArgumentException(
"invalid suit: " + suit);
}
this.rank = rank;
this.suit = suit;
}
Try Catch version:
try {
int rankInt = Integer.parseInt(rankStr);
int suitInt = Integer.parseInt(suitStr);
card = new Card(rankInt, suitInt);
}
catch (NumberFormatException exc) {
card = new Card(rankStr, suitStr);
}
System.out.println("Your card is: " + card);
Enums Activity
Months
In JShell add:
public enum Month {
JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC;
}
Then type out:
�Month m = null;
m = JUN;
m = Month.JUN;��m.toString()
Month spring = Month.MAR;
Month summer = Month.JUN;
m == spring
m == summer
Month.JUL = summer;
Months 2
Continuing:
m.ordinal()
spring.ordinal()
Month.OCT.ordinal()
m.compareTo(spring)
m.compareTo(Month.OCT)
m = Month.valueOf("Mar");
m = Month.valueOf("MAR");
m == spring
m = Month.valueOf(5);
m = new Month("HEY");
Month[] all = Month.values();
all[0]
all[11]
all[12]
PI Question
Consider the variables JAN, FEB, MAR, etc. Based on how they were used:
a) Are they public? b) Are they static? c) Are they final?