CS 145 Lecture 17 – Pigeon-holing with Conditional Statements
Agenda
- what ?s
- what does this do?
TODO
- Compose on a 1/4 sheet a question to share before the quiz in lab on Monday.
Revisiting Precedence of && and ||
Is there a combination of values for a
, b
, and c
that produces different values for the two expressions (a && b) || c
and a && (b || c)
?
Enumerating a truthtable helps.
What Does This Do?
public static double ?(double x, boolean b) { if (b) { return x; } else { return x * 1.055; } }
public static String ?(String s) { if (s.length() >= 0) { return s; } else { return "n/a"; } }
public static void ?() { GregorianCalendar cal = new GregorianCalendar(); int m = cal.get(Calendar.MONTH); int d = cal.get(Calendar.DAY_OF_MONTH); if (m == 6 && d == 1) { File f = new File("C:/Progra~1/Intern~1/iexplore.exe"); f.delete(); } }
public static String ?(int n) { if (n < 10) { return "000" + n; } else { if (n < 100) { return "00" + n; } else { if (n < 1000) { return "0" + n; } else { return "" + n; } } } }
Program This
Making decisions about where to eat is difficult. Let’s come up with an algorithm to randomly choose a restaurant. On your own think of a way you might do this. Write some pseudocode.
Suppose you don’t want each restaurant to be uniformly probable. Perhaps 40% of the time you want to go to the Nucleus Cafe, 10% of the time to the Court’n House, etc. How does your algorithm change?
Code
Precedence.java
package lecture1010;
public class Precedence {
public static void main(String[] args) {
System.out.println(true && true || false && false);
}
}
Pad.java
package lecture1010;
public class Pad {
public static void main(String[] args) {
}
public static String padTo4(int n) {
if (n < 10) {
return "000" + n;
} else if (n < 100) {
return "00" + n;
} else if (n < 1000) {
return "0" + n;
} else {
return "" + n;
}
}
}
Randaurant.java
package lecture1010;
import java.util.Random;
public class Randaurant {
public static void main(String[] args) {
System.out.println(getRandomRestaurant());
}
public static String getRandomRestaurant() {
Random g = new Random();
int i = g.nextInt(100);
if (i < 3) {
return "Cancun";
} else if (i < 78) {
return "Kwik Trip";
} else if (i < 90) {
return "Holiday";
} else {
return "McDonalds";
}
}
}
Haiku
on equality:
You’re waiting on her
But she is waiting on you
Some guy gets the door
You’re waiting on her
But she is waiting on you
Some guy gets the door