Programming and Computer Science in Java:

See Course Home Page.

This lab runs the week of Monday, February 10, 2003. Remember that you may not look at other students' code, nor can you show your code to other students.

Every problem in this lab, plus any reasonable variant of those problems, may appear on quizzes and tests following this lab. Study these very carefully!!!

Good luck.

DK

- PSVM / Hello World
- Integer Variables
- Double Variables
- If Statement
- While Statement
- Math Operators and Methods
- String Variables
- More Problems
- Upcoming Topics
- Your Own Methods
- Random Numbers
- String Methods
- Logical Operators
- Boolean Variables
- Recursion
- Arrays
- Graphics
- Sorting Algorithms

The following code implements "Hello World":

/* You can change "MyClass" to any name, but it should be capitalized, and it must correspond to your project settings. In Java, if your file is named Foo.java, then it must define a class named Foo. */ class MyClass { public static void main(String[] args) { // Print out a nice message on its own line System.out.println("Howdy!"); } }

What you must understand here:

- The enclosing "class" statement
- The PSVM (public static void main) syntax
- How to use squiggly braces with proper indenting
- How to create single-line comments with //
- How to create multi-line comments with /* */
- How to print out a string use System.out.println("foo");

[ top of document ]

**Problems: PSVM / Hello World**

__Problem 1: Print out Your Name__

Write a Java program which prints out your name on a line by itself.

__Problem 2: Knock-Knock Joke__

Write a Java program which prints out a Knock-Knock joke. The output
should be 5 lines of text, something like the following (but you must use your
own joke, and it should be both funny and tasteful):

Knock knock.

Who's there?

Panther.

Panther who?

Panther no pants, I'm going swimming!

[ top of document ]

The following code demonstrates use of integer variables:

class MyClass { public static void main(String[] args) { int x,y; // declaration x = 10; // assignment y = 20; // assignment System.out.println("x = " + x); // output System.out.println("y = " + y); x = 3/2; // integer division (result is 1) System.out.println("3/2 = " + x); y = 2 + x * 6 + 5; // precedence: 2 + (x * 6) + 5 System.out.println("y = " + y); // now demonstrate how to read an integer from user input System.out.print("Enter an integer: "); x = console.readInt(); System.out.println("You entered: " + x); } // Must include following in order to use console in main() public static TextReader console = new TextReader(System.in); }

What you must understand here:

- How to declare integer variables
- How to assign values into variables
- How to use println to print out variable values
- Integer math operators: + - * /
- How integer division works (truncation towards zero)
- How operator precedence works
- How to read an integer from user input
- This includes declaring the "console" object outside your PSVM but inside the enclosing class.
- This also includes using an appropriate
*prompt*for the input.

[ top of document ]

**Problems: Integer Variables**

__Problem 3: Fahrenheit to Celsius__

Write a Java program which converts from Fahrenheit to Celsius using integer
math. Note that 212 degrees Fahrenheit is 100 degrees Celsius, and 32
degrees Fahrenheit is 0 degrees Celsius. Be sure to include a clear user
interface (that is, a clear prompt for input, and a clear explanation of the
output).

__Problem 4: Kilometers to Miles
__Write a Java program which converts Kilometers to Miles using integer
math. If you do not know the conversion, use the Internet to look it up.

[ top of document ]

The following code demonstrates use of double variables:

class MyClass { public static void main(String[] args) { double x,y; // declaration x = 10.5; // assignment y = 20; // assignment System.out.println("x = " + x); // output System.out.println("y = " + y); // Here we see integer division stored in a double. // Because 3 and 2 are both integers, 3/2 uses INTEGER // division, and so the result is 1 and NOT 1.5 x = 3/2; // integer division (result is 1) System.out.println("3/2 = " + x); // However, if either the numerator or the denominator // is a double, then the division is double division. // Thus, 3/2.0 uses DOUBLE division, so the result // is 1.5 and NOT 1 x = 3/2.0; // double division (result is 1.5) System.out.println("3/2.0 = " + x); // now demonstrate how to read a double from user input System.out.print("Enter a double: "); x = console.readDouble(); System.out.println("You entered: " + x); } // Must include following in order to use console in main() public static TextReader console = new TextReader(System.in); }

What you must understand here:

- How to declare double variables
- How to assign values into variables
- How to use println to print out variable values
- Double math operators: + - * /
- How double division works
- How operator precedence works
- How to read a double from user input

[ top of document ]

**Problems: Double Variables**

__Problem 5: Fahrenheit to Celsius__

Write a Java program which converts from Fahrenheit to Celsius using *double*
math. Note that 212 degrees Fahrenheit is 100 degrees Celsius, and 32
degrees Fahrenheit is 0 degrees Celsius. Be sure to include a clear user
interface (that is, a clear prompt for input, and a clear explanation of the
output). *Note how this program differs from the integer-based version
from the previous section.*

__Problem 6: Kilometers to Miles
__Write a Java program which converts Kilometers to Miles using

[ top of document ]

The following code demonstrates use of the "if" statement:

class MyClass { public static void main(String[] args) { // first load some value into "x" int x; System.out.print("Enter a number: "); x = console.readInt(); // Demonstrate using "if" alone: check if x is 32 if (x == 32) { System.out.println("You entered the number 32"); } // Demonstrate using "if/else": check if x is even or odd if ((x / 2) * 2 == x) { System.out.println(x + " is even"); } else { System.out.println(x + " is odd"); } // Demonstrate using "if/else if/else": // check if x is positive, zero, or negative if (x > 0) { System.out.println(x + " is positive"); } else if (x == 0) { System.out.println(x + " is zero"); } else { System.out.println(x + " is negative"); } } }

What you must understand here:

- Basic structure of an "if" statement:

if (test)

{

BODY

} - In particular, note that:
- The test is always in parentheses
- The test always returns
*true*or*false* - There is never a semicolon after the test!
- To test for equality, use two equals (==) and not just one equals (=)
- The body is always in squiggly braces (well, for now....)

- Basic structure of an "if-else" statement

if (test)

{

BODY

}

else

{

BODY

} - Basic structure of an "if-else if-else if-else" statement

if (test1)

{

BODY

}

else if (test2)

{

BODY

}

else if (test3)

{

BODY

}

else

{

BODY

}

[ top of document ]

**Problems: If statement**

__Problem 7: Larger of two numbers__

Write a Java program which reads in two integers and prints out the larger of
the two.

__Problem 8: Manhattan Distance
__Write a Java program which reads in four integers: x1, y1, x2, y2 (in
order), which represent two points (x1,y1) and (x2,y2) on a grid. Print
out the “Manhattan” distance from (x1,y1) to (x2,y2). As we discussed,
this is the distance one must walk in Manhattan from an intersection at (x1,y1)
to an intersection at (x2,y2). As there are buildings in your way, you
must walk straight down the x axis, and then straight down the y axis. The
answer would simply be the sum of (x2 - x1) and (y2 - y1), except that x2 might
be smaller than x1 (and, similarly, y2 might be smaller than y1), and your
program must use "if" statements to properly handle this case.

[ top of document ]

The following code demonstrates use of the "while" statement:

class MyClass { public static void main(String[] args) { // first load some value into "x" int x, counter; System.out.print("Enter a number: "); x = console.readInt(); // now use a while loop to print numbers from 0 to x counter = 0; while (counter < x) { System.out.println(counter); counter = counter + 1; } // now show how to use while (true) with a break. // We use this construct when the loop termination // condition is not readily checkable at the start // of the loop, but is easy to check in the middle of // the loop. // Here, for instance, we loop until the user enters 0. while (true) { System.out.print("Enter a number [0 to quit]: "); x = console.readInt(); if (x == 0) { // user entered 0, so quit the while loop. break; } System.out.println(x + " is not 0. Please try again."); } } }

What you must understand here:

- Basic structure of a "while" statement:

while (test)

{

BODY

} - In particular, note the following rules, which all apply to "if"
and "while" statements:
- The test is always in parentheses
- The test always returns
*true*or*false* - There is never a semicolon after the test!
- To test for equality, use two equals (==) and not just one equals (=)
- The body is always in squiggly braces (well, for now....)

- How to use a while statement to iterate some variable from "lo"
to "hi"

x = lo;

while (x <= hi)

{

BODY

x = x + 1;

} - Basic structure of a "while (true)" statement and the
"break" statement

while (true)

{

BODY

if (terminationTest)

{

break;

}

MORE BODY

}

[ top of document ]

**Problems: While Statement**

__Problem 9: Sum of Integers in a Range__

Write a Java program which reads in two integers and prints out the sum of the
numbers which are exclusively between those two integers. Note that your
program must work properly whether the larger number is entered first or second.

__Problem 10: Prime Test
__Write a Java program which reads in an integer N, and prints out whether or
not N is prime.

__Problem 11: Repeating Prime Test
__Write a Java program which repeatedly reads in an integer N, quitting when N
is non-positive (that is, when N <= 0), and prints out whether or not N is
prime.

__Problem 12: Simple Statistics
__Write a Java program which first reads in an integer N, followed by N
doubles, and then prints out the following information:

a) The largest double entered;

b) The smallest double entered;

c) The sum of all the doubles entered;

d) The average of all the doubles entered.

[ top of document ]

**Topic: Math Operators and Methods**

The following code demonstrates use of various Math operators and methods:

class MyClass { public static void main(String[] args) { double d, e; int i, x, y; // Casting a double into an integer d = 1.987; i = (int) d; // truncates d, so i = 1 System.out.println("d = " + d + ", casted to an int i = " + i); // Casting an integer into a double. System.out.println("3/2 = " + (3/2)); System.out.println("(double)(3/2) = " + (double)(3/2)); System.out.println("(double)(3)/2 = " + (double)(3)/2); // now demonstrate integer operators and methods System.out.println(); System.out.println("Now demonstrating integer operators and methods."); while (true) { System.out.print("Enter two integers [0's to exit]: "); x = console.readInt(); y = console.readInt(); if ((x == 0) && (y == 0)) { break; } System.out.println("Math.abs(" + x + ") = " + Math.abs(x)); System.out.println(x + " % " + y + " = " + (x % y)); System.out.println("Math.max(" + x + "," + y + ") = " + Math.max(x,y)); System.out.println("Math.min(" + x + "," + y + ") = " + Math.min(x,y)); } // now demonstrate double operators and methods System.out.println(); System.out.println("Now demonstrating double operators and methods."); System.out.println("Math.PI = " + Math.PI); System.out.println("Math.E = " + Math.E); while (true) { System.out.print("Enter two doubles [0's to exit]: "); d = console.readInt(); e = console.readInt(); if ((d == 0) && (e == 0)) { break; } System.out.println("Math.abs(" + d + ") = " + Math.abs(d)); System.out.println("Math.round(" + d + ") = " + Math.round(d)); System.out.println("Math.sqrt(" + Math.abs(d) + ") = " + Math.sqrt(Math.abs(d))); System.out.println("Math.exp(" + d + ") = " + Math.exp(d)); System.out.println("Math.log(" + Math.abs(d) + ") = " + Math.log(Math.abs(d))); System.out.println("Math.sin(" + d + ") = " + Math.sin(d)); System.out.println("Math.cos(" + d + ") = " + Math.cos(d)); System.out.println("Math.tan(" + d + ") = " + Math.tan(d)); System.out.println("Math.max(" + d + "," + e + ") = " + Math.max(d,e)); System.out.println("Math.min(" + d + "," + e + ") = " + Math.min(d,e)); System.out.println("Math.pow(" + d + "," + e + ") = " + Math.pow(d,e)); } // Finally, demonstrate 10 random numbers: System.out.println("Here are 10 random numbers:"); i = 0; while (i < 10) { System.out.println(Math.random()); i = i + 1; } } }

What you must understand here:

*Casting*a double into an integer.*Casting*an integer into a double.- The modulus (%) operator: (x % y) is the
*remainder*when x is divided by y. - Math.abs(x) takes the
*absolute value*of x (works for integers or doubles) - Math.max(a,b) takes the
*maximum*of a and b (works for integers or doubles) - Math.min(a,b) takes the
*minimum*of a and b (works for integers or doubles) - Math.PI is the constant PI (3.14159265358...)
- Math.E is the constant E (2.718281828459...)
- Math.round(d)
*rounds*d to the nearest integer - Math.sqrt(d) takes the
*square root*of d - Math.pow(c,d) raises c to the d
^{th}power (that is, it equals c^{d}) - Math.exp(d) raises
*e*(2.718...) to the d^{th}power (that is, it equals e^{d}) - Math.log(d) takes the
*natural logarithm (base e -- 2.718...)*of d - Math.sin(d) takes the
*sine*of d, where d is in*radians*- To convert degrees to radians: (2 * Math.PI * (degrees / 360))

- Math.cos(d) takes the
*cosine*of d, where d is in*radians* - Math.tan(d) takes the
*tangent*of d, where d is in*radians* - Math.random() returns a random double in [0.0,1.0]

[ top of document ]

**Problems: Math Functions**

__Problem 13: Area of a Circle__

Write a Java program which reads in a double which is the radius of a circle,
and prints out the area of that circle.

__Problem 14: Radius of a Circle
__Write a Java program which reads in a double which is the area of a circle,
and prints out the radius of that circle.

__Problem 15: An Improved Prime Test
__Write a Java program which reads in an integer N, and prints out whether or
not N is prime. However, you must use the modulus operator (%) to test if
a number is evenly divisible by another. Also, you must only test for
division against the

__Problem 16: Analyzing the Improved Prime Test
__Here, we compare the run times of our improved prime test against our
original prime test. To do this, make a table (on a piece of paper) with
three columns -- N, Seconds for Test 1, and Seconds for Test 2. In the
first column, place different values of N, say 100, 1000, 10k, 100k. In
the second and third columns, place the corresponing number of seconds the
appropriate programs required on that input. Plot these values on a
graph. Make some conclusions about how well or poorly your improved prime
test runs, trying to be as specific as possible.

__Problem 17: Point in Unit Circle
__Read in two doubles, x and y, and print out whether the point (x,y) falls
within the unit circle. Note that this is true if and only if x

[ top of document ]

The following code demonstrates basic use of String variables:

class MyClass { public static void main(String[] args) { String s; int i; while (true) { System.out.print("Enter a string ['done' to quit]: "); s = console.readWord(); // note it is readWord, not readString // note that we use s.equals("done"), not (s == "done") if (s.equals("done")) { break; } System.out.println("You entered: " + s); // Demonstrate string concatentation with "+" s = "Wahoo:" + s; System.out.println("Now s = " + s); // Demonstrate finding the length of s System.out.println("Length of s: " + s.length()); // Demonstrate finding individual characters within s System.out.println("Demonstrating how to access each character in s:"); i = 0; while (i < s.length()) { System.out.print(" s.charAt(" + i + ") = " + s.charAt(i)); if (s.charAt(i) == 'h') { System.out.print(" [ this is an 'h' ] "); } System.out.println(); i = i + 1; } } } // Must include following in order to use console in main() public static TextReader console = new TextReader(System.in); }

What you must understand here:

- How to declare String variables
- How to assign values into String variables
- How to use println to print out String variable values
- String concatentation operator: +
- String comparisons: s.equals("done") and not (s == "done")
- How to find String length using s.length()
- How to read a String from user input (readWord() not readString())
- How to access an individual character in the string: s.charAt(i)
- This is 0-based, so the first character is s.charAt(0)
- This returns a
*character*which is*not*a string - You can test if it is a particular character as follows:

s.charAt(i) == 'h'

Note that 'h' uses*single-quotes*, since it is the*character*h and*not the string "h"* - You can compare two characters in the string directly, so to test if
the first and second characters are the same, you may test:

s.charAt(0) == s.charAt(1)

[ top of document ]

**Problems: String Variables**

__Problem 18: Longest Name__

Write a Java program which reads in a positive integer N followed by N last
names. Your program should print out the longest last name (in the case of
a tie, print out the first one entered).

__Problem 19: Palindrome
__Write a Java program which repeatedly reads in a word, quitting when the
user enters "done", and prints out whether or not that word is a
palindrome. That is, whether it is the same backwards as forwards.
Some palindromes: "mom", "dad", "madam",
"detartrated", as well as nonsensical words such as "foof",
"abccba", and so forth.

[ top of document ]

__Problem 20: Factorial__

Write a Java program which repeatedly reads in a positive integer n (quitting
when n <= 0), and prints out n factorial, where n! = n * (n-1) * (n-2) * ...

__Problem 21: Triangle Area
__Write a Java program which reads in the width and height (as doubles) of a
triangle, and prints out the area of that triangle.

__Problem 22: Making Change
__Write a Java program which reads in an integer in [0,100), and makes
appropriate change for that many cents. So, if the user enters, say, 73,
your program should print that the change is 2 quarters, 2 dimes, and 3 pennies.

__Problem 23: Legal Triangle
__Write a Java program which reads in three sides (as integers) of a triangle,
and prints out whether or not those sides constitute a legal triangle.
Note that a triangle is only legal if the sum of any two sides is greater than
the third side. So, 2, 3, 10 is

__Problem 24: Sum of Perfect Squares to n
__Write a Java program which repeatedly reads in a positive integer n
(quitting when n <= 0), and prints out the sum of the perfect squares which
are less than or equal to n. That is, print out 1

__Problem 25: Slope of a Line
__Write a Java program which reads in four doubles, x1, y1, x2, y2.
Print out the slope of the line which goes through the points (x1,y1) and
(x2,y2). If the line is vertical, print out an appropriate message (you
may not just crash!).

__Problem 26: Parabola Crosses the X Axis?
__Write a Java program which reads in three doubles, a, b, and c, prints out
where the parabola y = ax

__Problem 27: Perimeter of a Regular Polygon
__ Read in the name of a regular polygon and a side length, and output the
perimeter of that polygon. The polygon will be a triangle, square, pentagon, hexagon, heptagon, or octagon.
For example, if the input is

__Problem 28: Prime Factorization
__Write a Java program which repeatedly reads in an integer n (quitting when n
<= 1) and prints out the prime factorization of n, where the primes are
listed in increasing order. So, for instance, if the user inputs

__Problem 29: Infinite Exponentiation, Finite Answer__

Read in a positive double y and output the positive double x such that the infinite exponentiation of x equals y, that is: x^(x^(x^(x^(x^(x^(x^(x^(x...)))...) = y.

__Problem 30: Intersecting Lines
__Write a Java program which reads in four doubles: m1, b1, m2,
b2. These represent the lines y = m1 * x + b1, and y = m2 * x + b2.
Print out the point (x,y) where these two lines intersect. If the two
lines are the same line, or if they are parallel, print out appropriate
messages.

__Problem 31:__ a^{b}c^{d} = abcd__
__Write a Java program which finds the single-digit numbers a, b, c, and d such that
a

__Problem 32: Hamming Distances
__Read in an integer N followed by a word W followed by N more words of the same length as W. Output the word after W which is "closest" by Hamming Distance to W -- that is, the one which differs by the fewest characters from W.

Sample Input: 4 port pond tart post cork

Sample Output: post

__Upcoming Problems:__

- Finding PI using darts
- Confirming Goldbach's Conjecture
- Sorting arrays
- Graphics!!!
- Gaussian elimination (solving systems of linear equations)

[ top of document ]

See Course Home Page.