1 of 7

Lecture 12 - CS 159 Exceptions + Enums

Prof. Alvin Chao

Due this week:

  • Thu 11pm Lab Junit
  • Fri Quiz classes+enum
  • HW4 Sun 11pm
  • —Next week
  • Mon Lab enums

2 of 7

Exceptions Activity

3 of 7

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);

4 of 7

Enums Activity

5 of 7

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;

6 of 7

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]

7 of 7

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?

https://canvas.jmu.edu/courses/2071161/assignments/19825645