Programming and Computer Science in Java:
Lab:  First 32 Problems
    David Kosbie, 2002-2003
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

Topics:

  1. PSVM / Hello World
  2. Integer Variables
  3. Double Variables
  4. If Statement
  5. While Statement
  6. Math Operators and Methods
  7. String Variables
  8. More Problems
  9. Upcoming Topics
    1. Your Own Methods
    2. Random Numbers
    3. String Methods
    4. Logical Operators
    5. Boolean Variables
    6. Recursion
    7. Arrays
    8. Graphics
    9. Sorting Algorithms

Topic:  PSVM / Hello World

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:

  1. The enclosing "class" statement
  2. The PSVM (public static void main) syntax
  3. How to use squiggly braces with proper indenting
  4. How to create single-line comments with //
  5. How to create multi-line comments with /*  */
  6. 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 ]


Topic:  Integer Variables

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:

  1. How to declare integer variables
  2. How to assign values into variables
  3. How to use println to print out variable values
  4. Integer math operators:  +    -   *    /
  5. How integer division works (truncation towards zero)
  6. How operator precedence works
  7. How to read an integer from user input
    1. This includes declaring the "console" object outside your PSVM but inside the enclosing class.
    2. 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 ]


Topic:  Double Variables

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:

  1. How to declare double variables
  2. How to assign values into variables
  3. How to use println to print out variable values
  4. Double math operators:  +    -   *    /
  5. How double division works
  6. How operator precedence works
  7. 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 double math.  If you do not know the conversion, use the Internet to look it up.  Note how this program differs from the integer-based version from the previous section.

[ top of document ]


Topic:  If Statement

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:

  1. Basic structure of an "if" statement:
    if (test)
    {
         BODY
    }
  2. In particular, note that:
    1. The test is always in parentheses
    2. The test always returns true or false
    3. There is never a semicolon after the test!
    4. To test for equality, use two equals (==) and not just one equals (=)
    5. The body is always in squiggly braces (well, for now....)
  3. Basic structure of an "if-else" statement
    if (test)
    {
         BODY
    }
    else
    {
         BODY
    }
  4. 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.  Hint:  you may wish to introduce some variables named largerX, largerY, smallerX, and smallerY.

[ top of document ]


Topic:  While Statement

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:

  1. Basic structure of a "while" statement:
    while (test)
    {
         BODY
    }
  2. In particular, note the following rules, which all apply to "if" and "while" statements:
    1. The test is always in parentheses
    2. The test always returns true or false
    3. There is never a semicolon after the test!
    4. To test for equality, use two equals (==) and not just one equals (=)
    5. The body is always in squiggly braces (well, for now....)
  3. How to use a while statement to iterate some variable from "lo" to "hi"
    x = lo;
    while (x <= hi)
    {
         BODY
         x = x + 1;
    }
  4. 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:

  1. Casting a double into an integer.
  2. Casting an integer into a double.
  3. The modulus (%) operator:  (x % y) is the remainder when x is divided by y.
  4. Math.abs(x) takes the absolute value of x (works for integers or doubles)
  5. Math.max(a,b) takes the maximum of a and b (works for integers or doubles)
  6. Math.min(a,b) takes the minimum of a and b (works for integers or doubles)
  7. Math.PI is the constant PI (3.14159265358...)
  8. Math.E is the constant E (2.718281828459...)
  9. Math.round(d) rounds d to the nearest integer
  10. Math.sqrt(d) takes the square root of d
  11. Math.pow(c,d) raises c to the dth power (that is, it equals cd)
  12. Math.exp(d) raises e (2.718...) to the dth power (that is, it equals ed)
  13. Math.log(d) takes the natural logarithm (base e -- 2.718...) of d
  14. Math.sin(d) takes the sine of d, where d is in radians
    1. To convert degrees to radians:  (2 * Math.PI * (degrees / 360))
  15. Math.cos(d) takes the cosine of d, where d is in radians
  16. Math.tan(d) takes the tangent of d, where d is in radians
  17. 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 odd numbers (though you must test for division against 2 to handle all the even numbers).  Finally, you must only test for division up to the first integer larger than the square root of N.

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 x2 + y2 <= 1.

[ top of document ]


Topic:  String Variables

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:

  1. How to declare String variables
  2. How to assign values into String variables
  3. How to use println to print out String variable values
  4. String concatentation operator:  +
  5. String comparisons:  s.equals("done") and not (s == "done")
  6. How to find String length using s.length()
  7. How to read a String from user input (readWord() not readString())
  8. How to access an individual character in the string:  s.charAt(i)
    1. This is 0-based, so the first character is s.charAt(0)
    2. This returns a character which is not a string
    3. 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"
    4. 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 ]


Problems:  More Problems

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 not legal, since 2+3<10.

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 12 + 22 + 32 + ... + k2, where k2 <= n and (k+1)2 > n.

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 = ax2 + bx + c crosses the x axis (that is, where y = 0).  These are called the real zeroes of the parabola.  Note that it may do so zero times, one time, or two times, and you must handle all three cases.   To solve this problem, you will want to use the quadratic formula.

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 pentagon 19 your program should output that the perimeter is 95 (which is 19 * 5).

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 45, your program should output 3*3*5Hint:  you do not have to include a prime test in this program -- just keep dividing by numbers from 2 to n, each time you find one, say d, which divides n evenly, print d out and divide n by d and continue.  Think about this carefully.

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:  abcd = abcd
Write a Java program which finds the single-digit numbers a, b, c, and d such that abcd = abcd.  Output the 4-digit number abcd.  Note that your program must compute the answer, and not just print it out directly. 

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:

[ top of document ]


See Course Home Page