CS 100: Lecture L3
February 2
// Example L3A: Odds and Ends import java.io.*; public class L3A { public static void main( String args[]){ // initialize Text object in to read from standard input. TokenReader in = new TokenReader(System.in); // Example 1. // Declaring variables, the type int, assignment statements int x; System.out.println("Enter an integer: "); x = in.readInt(); int y; y = 3; int z = x + y; x = 2*x + y; System.out.println("\nx = " + x + " and z = " + z); // Example 2. // When does a 3-digit number have the same value when digits are written in // reverse order? int n, H, U; System.out.println("\n\nEnter a 3-digit integer:"); n = in.readInt(); H = n/100; // Integer division. U = n%10; // The remainder. if (H == U) { // The value in the ones place and the hundreds place is the same. System.out.println("Palindrome"); } else { // The value in the ones place and the hundreds place differs. System.out.println("Not a palindrome"); } // Example 3. // For any nonnegative real number a there is a nonegative integer m // and a real number r so that a = m*(2pi) + r and 0<=r<2pi. double a, m, r; a = 20.5; m = Math.floor(a/(2*Math.PI)); r = a - m*2.0*Math.PI; // Note that r = a % (2.0*Math.PI) does not work. System.out.println("\n\n a = " + a + ", m = " + m + ", r = " + r); // Example 4. // Assign the 13th decimal digit of pi to integer variable d13 double b; long bLong; int d13; b = Math.pow(10,13)*Math.PI; bLong = (long) b; d13 = (int)(b % 10); // Use long instead of int if very big integers arise. System.out.println("\n\nThe 13th decimal in " + Math.PI + " is " + d13); /* The largest value that an int variable can hold is 2,147,483,647 = 2^31 - 1 about 10^9 The largest value that a long variable can hold is 9,223,372,036,854,775,807 = 2^63 - 1 about 10^18 */ in.waitUntilEnter(); } }
// Example L3B: Draws a staircase in two ways import java.io.*; import java.awt.*; public class CUCSDrawing extends Frame { final int h0 = 100; final int v0 = 50; // The leftmost step has upper left corner (h0,v0). final int delh = 140; // The tread length. final int delv = 70; // The riser height. public void paint(Graphics g) { int h; int v; // Method 1 h = h0; v = v0; g.drawRect(h,v,delh,delv); h = h+delh; v = v+delv; g.drawRect(h,v,delh,delv); h = h+delh; v = v+delv; g.drawRect(h,v,delh,delv); h = h+delh; v = v+delv; // Method 2 h = h0; v = v0; int k; for (k=1;k<=3;k=k+1) { g.drawRect(h,v,delh,delv); h = h+delh; v = v+delv; } } } public class L3B { public static void main(String args[]) { CUCSDrawing d = new CUCSDrawing(); d.resize(1000,800); d.move(0,75); d.setTitle("L3B"); d.show(); d.toFront(); } }