CS 145 Lecture 6
September 26, 2011 by Chris Johnson. Filed under cs145, fall 2011, lectures.
Topics Covered
- what does this do?
- facing off the computer in guess-a-number
- generating a random spelunking workout
- an acrostic editor
- calculating average cell phone payment
What does this do?
-
public static String ?(??) {
return text + " :)";
}
show
-
public static ? ??(String text) {
return text.length() == 0;
}
show
-
public static ? ??(String text) {
int index = text.indexOf('.');
return text.substring(0, index + 1);
}
show
Code
GeometryFun.java
package lecture;
import java.util.Scanner;
public class GeometryFun {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter radius: ");
double value = in.nextDouble();
double area = getAreaOfCircle(value);
System.out.println("Area: " + area);
// getAreaOfCircle("t");
System.out.println(getAreaOfAnnulus(6, 8));
}
public static double getAreaOfCircle(double radius) {
double area = radius * radius * Math.PI;
// radius = 6.0; // this has absolutely no effect on anything at all
return area;
}
// meaningful name?
// return type?
// outside information?
public static double getAreaOfAnnulus(double insideRadius, double outsideRadius) {
double insideArea = getAreaOfCircle(insideRadius);
double outsideArea = getAreaOfCircle(outsideRadius);
double totalArea = outsideArea - insideArea;
return totalArea;
}
public static double f(double t) {
return 1 / (1 + Math.sqrt(t));
}
//
public static double getEdgeOfCube(double diagonalLength) {
// find diagonal of bottom face
double edgeLength = diagonalLength / Math.sqrt(3);
return edgeLength;
}
}
GuessANumber.java
package lecture;
import java.util.Random;
import java.util.Scanner;
public class GuessANumber {
public static void main(String[] args) {
// think of a number
// computer generate a #
// see if #s same
// respond to correctness
// computer generate a #
// see if #s same
// respond to correctness
Random generator = new Random();
boolean isSame = false;
Scanner in = new Scanner(System.in);
System.out.print("Your number in [0, 5]: ");
int answer = in.nextInt();
while (isSame == false) {
int guess = generator.nextInt(6); // number between 0 and 5
isSame = (answer == guess);
System.out.println("The computer's answer (" + guess + ") is right? " + isSame);
}
}
}
SpelunkingFitnessDisplay.java
package lecture;
import java.util.Random;
public class SpelunkingFitnessDisplay {
public static void main(String[] args) {
printLine();
}
public static void printLine() {
Random generator = new Random();
int nDots = generator.nextInt(11);
System.out.println(nDots);
while (nDots > 0) {
System.out.print("*");
nDots = nDots - 1;
}
}
}
TODO
- Read sections 3.1 through 3.3.
Haiku
still my loop goes on
why? some never even start
their conditions bad
show