PROG 10082
Object Oriented Programming 1

Mid Term 2 Review Solutions

Practice Questions

1. Find the errors in each of these code segments (each segment is from a different program):

a.

int c = keysIn.nextInt();
if (c => 7);
   System.out.println("c is less than 7");

b.

int product;
int c = keysIn.nextInt();
While (c <= 5 )
   product *= c;
   c++;

c.

public class Something {
   public static void main(String[] args) {
      int number = 5;
      do
      {
         double cube = Math.pow(number, 2);
      while (number > 0)
      }
   }
}

2. Find the Output:

a.

int i=5, j=10;
if (i < 5)
   System.out.println("foo");
   if (j >= 5)
      System.out.println("bar");
else
   System.out.println("yee");

The indentation doesn't matter here - the else block always goes with the if directly above when no braces are used. Additionally, since there are no braces, the first if-block only contains the println() statement; the if/else is separate. Rewritten with proper indentation:

int i=5, j=10;
if (i < 5)
   System.out.println("foo");
if (j >= 5)
      System.out.println("bar");
else
   System.out.println("yee");

Now you can see that because the first if (i < 5) is false, its block does not execute. Now we move on to the if-else below that: j >= 5 is true, so "bar" is printed. The else is skipped.

b.

int counter = 0, sum = 0;
do {
   System.out.println(counter++);
   sum += counter;
} while (counter <=5);
System.out.println(sum + ", " + counter);

Here you add the counter to the sum variable in each iteration, as you print the value of counter on individual lines. Note that counter is being incremented AFTER it is printed. At the end, the total value of sum and the value of counter are displayed:

values during iteration:
counter = 0 when printed, incremented to 1: sum = 1
counter = 1 when printed, incremented to 2: sum = 3
counter = 2 when printed, incremented to 3: sum = 6
counter = 3 when printed, incremented to 4: sum = 10
counter = 4 when printed, incremented to 5: sum = 15
counter = 5 when printed, incremented to 6: sum = 21

final output:

0
1
2
3
4
5
21, 6

c.

int counter = 1;
while (counter <=5) {
   System.out.print(counter + ": ");
   if (counter % 2 == 0)
      System.out.println("even");
   else
      System.out.println("odd");
}

Endless loop - you'll just get the output:
1: odd
over and over again because there's an increment missing!

d. (user enters "hello" and 4)

System.out.println("Enter a name.");
String name = keysIn.next();
keysIn.nextLine();
System.out.println("Enter a number.");
int num = keysIn.nextInt();

if (num % 2 == 0) {
   int counter = 0;
   while (counter <= num) {
      System.out.println(counter + " " + name);
      counter += 2;
   }
} else {
   int counter = num;
   do {
      System.out.println(name);
      counter--;
   } while (counter >= 1);
}

This will print:

0 hello
2 hello
4 hello

e. do question d again, where user enters "hello" and 3

This will print:

hello
hello
hello

f.

for (int row=1; row<=6; row++)
{
   int space;
   for (space=6; space>row; space--) {
      System.out.print(" ");
   }

   for (int col=space; col>=1; col--) {
      System.out.print(col);
   }
   System.out.println();
}

Here, your outer for-loop will execute 6 times. For each iteration of your outer loop, you have two inner loops. The first inner loop goes from 6 to row times (e.g. for first iteration of outer loop, 6 to 1; for 2nd iteration of outer loop, 6 to 2; 3rd iteration will be 6 to 3, etc.) This first inner loop will execute one fewer times for each iteration of the outer loop, so it should just print a row of 6 spaces, then 5 spaces, then 4 spaces, etc all the way to 1 space.

The second inner loop occurs after a row of spaces is printed. It counts its col value from the value of space down to 1. The value of space is different for each iteration of the outer loop: in the first iteration, it was counted down to 1 by the first inner loop; in the second iteration, it was counted down to 2 by the first inner loop; in the third iteration, it was counted down to 3, etc. So when the second inner loop begins, space will be used with the value it had been left with after the first inner loop completes. This means the second loop's first iteration goes from 1 to 1; the second iteration from 2 to 1, the third iteration from 3 to 1, etc.

This is why you get the following output:

     1
    21
   321
  4321
 54321
654321

Coding Questions

1. A company calculates the cost of shipping packages by the weight of the package. Packages have a tiered cost based on weight:

Up to 2 Kg: $1.15 per Kg
Up to 5 Kg: $1.35 per Kg
Up to 10 Kg: $1.75 per Kg
10 Kg and over: $2.00 per Kg

Write a program that prompts the user for the user to enter the package weight. Determine the cost per Kilogram based on the weight of the package. Then calculate and display the total shipping cost.

import java.util.*;

public class Mt2RevQu2 {

	public final static double TIER1 = 1.15;
	public final static double TIER2 = 1.35;
	public final static double TIER3 = 1.75;
	public final static double TIER4 = 2.0;
	public final static double WEIGHT_LMT_T1 = 2.0;
	public final static double WEIGHT_LMT_T2 = 5.0;
	public final static double WEIGHT_LMT_T3 = 10.0;

	public static void main(String[] args) {

		Scanner in = new Scanner(System.in);

		System.out.println("Enter package weight: ");
		double weight = in.nextDouble();
		rate = 0;

		if (weight < WEIGHT_LMT_T1) {
			rate = TIER1;
		} else if (weight < WEIGHT_LMT_T2) {
			rate = TIER2;
		} else if (weight < WEIGHT_LMT_T3) {
			rate = TIER3;
		} else {
			rate = TIER4;
		}

		double totalCost = rate * weight;
		System.out.printf("Total Cost $%.2f%n", totalCost);
	}
}

2. Write a program for a mall kiosk that handles ticket sales for a holiday charity event. The person manning the kiosk sells tickets to people passing by at $19.99 per ticket. If a person purchases 10 or more tickets, they get a 5% discount on the ticket price. Instead of purchasing tickets, people can make a donation of any amount they like. Your program should use a confirm dialog to ask the user if tickets are being purchased, in which case the number of tickets should be retieved via an input dialog, and the discount should be included if appropriate. If the person is not purchasing tickets, the donation amount should be retrieved via input dialog. After the values have been recorded, an "invoice" displaying the amount to collect should be displayed, formatted, on the screen in a dialog box.

import java.util.*;

public class Mt2RevQu2 {

	public final static double REG_PRICE = 19.99;
	public final static double DISC_PRICE = REG_PRICE * .95;
	public final static int NUM_DISC = 10;

	public static void main(String[] args) {

		Scanner in = new Scanner(System.in);

		double amtCollected = 0;
		System.out.print("Is customer buying tickets? (Y/N) ");
		char ans = Character.toUpperCase(in.next().charAt(0));
		
    if (ans == 'Y') {
			System.out.print("Enter # Tickets: ");
			int numTickets = in.nextInt();
			double price = REG_PRICE;

			if (numTickets > NUM_DISC)
				price = DISC_PRICE;

			amtCollected = price * numTickets;

		} else {
			System.out.print("Enter $Donation: ");
			amtCollected = in.nextDouble();
		}

		System.out.printf("Amount to Collect: $%.2f%n",
			amtCollected);
	}
}

3. Write a program using a for-loop that displays a conversion table for pounds and grams (one pound = 453.6 grams). The start and end value should be entered by the user. Example below:

Enter Start Value: 1
Enter End Value: 20

Conversion Table:  LBS to GRAMS
LBS             GRAMS
----            ------
 1.0             453.6
 2.0             907.2
 3.0            1360.8
 4.0            1814.4
 5.0            2268.0
 6.0            2721.6
 7.0            3175.2
 8.0            3628.8
 9.0            4082.4
10.0            4536.0
11.0            4989.6
12.0            5443.2
13.0            5896.8
14.0            6350.4
15.0            6804.0
16.0            7257.6
17.0            7711.2
18.0            8164.8
19.0            8618.4
20.0            9072.0

Extra: If the user enters a start value that's larger than the end value, swap the start and end values.

import java.util.*;

public class Mt2RevQu3 {

	public final static double CONVERT = 453.6;

	public static void main(String[] args) {

		Scanner in = new Scanner(System.in);

		System.out.print("Enter start value: ");
		int start = in.nextInt();
		System.out.print("Enter end value: ");
		int end = in.nextInt();

		// extra: ensure start/end in right order
		if (start > end) {
			int temp = start;
			start = end;
			end = temp;
		}

		System.out.println("Conversion Table:  LBS to GRAMS");
		System.out.printf("%-7s %-10s%n", "LBS", "GRAMS");
		System.out.println("-----   -------");

		for (int i=start; i<=end; i++) {
			double grams = i * CONVERT;
			System.out.printf("%5.1f %8.1f%n",
				(double)i, grams);
		}
	}
}