CS 145 Lecture 12 – Conditionals and file input
Agenda
- generating an ordinal number
- if/else if
- reading from files (brief treatise on exceptions)
- test-driven development
- categorizing light
Code
Ordinals.java
package lecture; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Ordinals { public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File("/home/cjohnson/Desktop/ordinals.txt")); while (in.hasNextInt()) { int i = in.nextInt(); String expected = in.next(); String actual = getOrdinal(i); if (!actual.equals(expected)) { System.out.println("Expected: " + expected + " but Actual: " + actual); } } in.close(); } public static String getOrdinal(int n) { int positiveN = Math.abs(n); if (positiveN % 100 >= 11 && positiveN % 100 <= 13) { // All numbers with 11,12,13 in units/tens places return n + "th"; } else if (positiveN % 10 == 1) { // All numbers with 1 in units place return n + "st"; } else if (positiveN % 10 == 2) { // All numbers with 2 in units place return n + "nd"; } else if (positiveN % 10 == 3) { return n + "rd"; } else { return n + "th"; } } }
Haiku
tests address less guess
showed code won’t explode on load
’bout routs doubt’s snout out
showed code won’t explode on load
’bout routs doubt’s snout out