CS 145 Lecture 11 – Conditionals
October 17, 2011 by Chris Johnson. Filed under cs145, fall 2011, lectures.
Agenda
What does this do?
-
public static boolean snarfFlob() {
return !isAlarmOn && (isHoliday || isWeekend);
}
-
public static int getFlooper(int n) {
if (n % 2 == 1) {
return n - 1;
} else {
return n;
}
}
-
public static int bupperBap(Scanner in) {
while (!in.hasNextInt()) {
in.next();
}
return in.nextInt();
}
Code
Conditional.java
package lecture;
public class Conditional {
public static void main(String[] args) {
star(100);
System.out.println(pluralize("Nick", 42));
System.out.println(pluralize("Nick", 1));
System.out.println(pluralize("Nick", -1));
System.out.println(pluralize("Nick", -87));
}
/*
* dog, 1 -> 1 dog
* dog, 5 -> 5 dogs
* child, 3 -> 3 childs
* moose, 4 -> 4 mooses
* code, 1 -> 1 code
*/
public static String pluralize(String object, int n) {
// String nonplural = n + " " + object;
// if (n == 1 || n == -1) {
// return nonplural;
// } else {
// return nonplural + "s";
// }
String answer = n + " " + object;
if (Math.abs(n) != 1) {
answer = answer + "s";
}
return answer;
}
public static void star(int nPoints) {
// walk around circumference of circle
// print each point (x, y)
double angle = 0.0;
double delta = 2.0 * Math.PI / nPoints;
for (int i = 0; i <= nPoints; ++i, angle += delta) {
// print out (x,y)-coordinate for this angle
if (i % 2 == 1) { // if odd
System.out.println(Math.cos(angle) * 0.5 + "," + Math.sin(angle) * 0.5);
} else { // if even
System.out.println(Math.cos(angle) + "," + Math.sin(angle));
}
}
}
}
TODO
- Read sections 4.2 – 4.4.