  Spring Semester 2003

Midterm One Makeup: Details on what to study etc. will be posted here soon.

Take a look at these problems. Problems on the exam will be just like these.

1. Find the errors in the following `if` statements.
```if quarters > 0 then System.out.println(quarters + "quarters");

if (1 + x > Math.pow(x, Math.sqrt(2)) y = y + x;

if (x = 1) y++; else if (x = 2) y = y + 2;

if (x && y == 0) p = new Point2D.Double(x, y);

if (1 <= x <= 10)
{ System.out.println("Enter y:");
}

if (s != "nickels" || s != "pennies"
|| s != "dimes" || s != "quarters")
System.out.print("Input error!");

if (input.equalsIgnoreCase("N") || "NO")
return;

int x = console.readDouble();
if (x != null) y = y + x;

language = "English";
if (country.equals("USA"))
if (state.equals("PR")) language = "Spanish";
else if (country.equals("China"))
language = "Chinese"; ```

2. Explain the following terms and give an example for each construct:

• Expression

• Condition

• Statement

• Simple statement

• Compound statement

• Block

3. Of the following pairs of strings, which comes first in lexicographic order?
```"Tom", "Dick"
"Tom", "Tomato"
"church", "Churchill"
"car manufacturer", "carburetor"
"Harry" hairy"
"C++", "Car"
"Tom", "Tom"
"Car", "Carl"
"car", "bar"```

4. Complete the following truth table by finding the truth values of the Boolean expressions for all combinations of the Boolean inputs `p`, `q`, and `r`.

`p` `q` `r` `(p && q) || !r` `!(p && (q || !r))`
false false false ? ?
false false true ? ?
false true false ? ?
? ? ? ? ?
? ? ? ? ?
? ? ? ? ?
? ? ? ? ?
? ? ? ? ?

5. True or false: `A && B ` is the same as `B && A ` for any Boolean conditions `A` and `B`?

6. Explain the difference between
```s = 0;
if (x > 0) s++;
if (y > 0) s++;```
and
```s = 0;
if (x > 0) s++;
else if (y > 0) s++;```

7. Use De Morgan's law to simplify the following Boolean expressions.
```!(x > 0 && y > 0)

!(x != 0 || y != 0)

!(country.equals("USA") && !state.equals("HI") && !state.equals("AK"))

!(x % 4 != 0 || !(x % 100 == 0 && x % 400 == 0))

```

8. Make up a Java code example that shows the dangling`-else` problem, using the following statement.
A student with a GPA of at least 1.5, but less than 2, is on probation.

With less than 1.5, the student is failing.

9. Explain the difference between the `==` operator and the `equals` method when comparing strings.

10. Explain the difference between the tests
`r == s`
and
`r.equals(s)`
where both `r` and `s` are of type `Rectangle`.

11. What is wrong with this test to see whether `r` is `null`? What happens when this code runs?
```Rectangle r;
...
if (r.equals(null))
r = new Rectangle(5, 10, 20, 30);```

12. Explain why it is more difficult to compare floating-point numbers than integers. Write Java code to test whether an integer `n` equals 10 and whether a floating-point number `x` equals 10.
```

```

13. Give an example for two floating-point numbers `x` and `y` such that

1. `Math.abs(x - y)` is larger than 1000,
2. but `x` and `y` are still identical except for a roundoff error.

```

```

14. Consider the following test to see whether a point falls inside a rectangle.
```Point2D.Double p = ...
boolean xInside = false;
if (x1 <= p.getX() && p.getY() <= x2)
xInside = true;
boolean yInside = false;
if (y1 <= p.getY() && p.getY() <= y2)
yInside = true;
if (xInside && yInside)
g2.drawString("p is inside the rectangle.", x1, y1);```
Rewrite this code to eliminate the explicit `true` and `false` values, by setting `xInside` and `yInside` to the values of Boolean expressions.
```

```

Now here are some more (selected) problems:

 1. Write a program (called `One`) that prints all real solutions to the quadratic equation a x2 + b x + c = 0 Read in a, b, c and use the quadratic formula. If the discriminant b2 - 4ac is negative, display a message stating that there are no real solutions. Here's how your program should behave: ```frilled.cs.indiana.edu%java One Please enter the value of a then press Enter : 1.0 Please enter the value of b then press Enter : -2.0 Please enter the value of c then press Enter : 1.0 2.0 2.0 frilled.cs.indiana.edu%java One Please enter the value of a then press Enter : 1 Please enter the value of b then press Enter : 0 Please enter the value of c then press Enter : 1 There are no solutions. frilled.cs.indiana.edu%java One Please enter the value of a then press Enter : 1 Please enter the value of b then press Enter : 2 Please enter the value of c then press Enter : 3 There are no solutions. frilled.cs.indiana.edu%java One Please enter the value of a then press Enter : 1 Please enter the value of b then press Enter : -3 Please enter the value of c then press Enter : 1 1.881966011250105 4.118033988749895 frilled.cs.indiana.edu%java One Please enter the value of a then press Enter : 0 Please enter the value of b then press Enter : 0 Please enter the value of c then press Enter : 3 3.0 is not zero frilled.cs.indiana.edu%java One Please enter the value of a then press Enter : 1 Please enter the value of b then press Enter : 0 Please enter the value of c then press Enter : 0 -0.0 0.0 frilled.cs.indiana.edu%java One Please enter the value of a then press Enter : 0 Please enter the value of b then press Enter : 0 Please enter the value of c then press Enter : 0 Identity: zero == zero. frilled.cs.indiana.edu%```

2. Write a program (called `Two`) that takes user input describing a playing card in the shorthand notation described below, and then prints the full description of the card.
 A Ace 2..10 Card values J Jack Q Queen K King
 D Diamonds H Hearts S Spades C Clubs
Here's a sample run of such a program:
```frilled.cs.indiana.edu%java Two
Enter the card notation: AS
frilled.cs.indiana.edu%java Two
Enter the card notation: 2H
Two of hearts.
frilled.cs.indiana.edu%java Two
Enter the card notation: CJ
Unknown denomination of unknown colour.
frilled.cs.indiana.edu%java Two
Enter the card notation: JC
Jack of clubs.
frilled.cs.indiana.edu%java Two
Enter the card notation: QK
Queen of unknown colour.
frilled.cs.indiana.edu%java Two
Enter the card notation: QH
Queen of hearts.
frilled.cs.indiana.edu%java Two
Enter the card notation:  A D
Unknown denomination of unknown colour.
frilled.cs.indiana.edu%java Two
Enter the card notation: A D
Ace of unknown colour.
frilled.cs.indiana.edu%java Two
Enter the card notation: AD
Ace of diamonds.
frilled.cs.indiana.edu%```

 3. Write a program (called `Three`) that reads in three floating-point numbers and prints the largest of the three inputs Here are (essentially) all possible runs of your program: ```frilled.cs.indiana.edu%java Three Please enter the value of a then press Enter : 1 Please enter the value of b then press Enter : 2 Please enter the value of c then press Enter : 3 The largest number is: 3.0 frilled.cs.indiana.edu%java Three Please enter the value of a then press Enter : 1 Please enter the value of b then press Enter : 3 Please enter the value of c then press Enter : 2 The largest number is: 3.0 frilled.cs.indiana.edu%java Three Please enter the value of a then press Enter : 2 Please enter the value of b then press Enter : 1 Please enter the value of c then press Enter : 3 The largest number is: 3.0 frilled.cs.indiana.edu%java Three Please enter the value of a then press Enter : 2 Please enter the value of b then press Enter : 3 Please enter the value of c then press Enter : 1 The largest number is: 3.0 frilled.cs.indiana.edu%java Three Please enter the value of a then press Enter : 3.0 Please enter the value of b then press Enter : 1.0 Please enter the value of c then press Enter : 2.0 The largest number is: 3.0 frilled.cs.indiana.edu%java Three Please enter the value of a then press Enter : 3.0 Please enter the value of b then press Enter : 2.0 Please enter the value of c then press Enter : 1.0 The largest number is: 3.0 frilled.cs.indiana.edu%```

 4. Write a program (called `Four`) that creates a circle with radius 100 and center (110, 120). Ask the user to specify the x and y coordinates of a point. If the point lies inside the circle, then show a message "Congratulations!" Otherwise, show a message "You missed." Feel free to use, and enhance with a method `public boolean contains(double xPoint, double yPoint){ ... }` the `Circle` class that we developed in the second set of problems. Here's a sample run of such a program: ```frilled.cs.indiana.edu%java Four Welcome. Circle created. Center is at: (110.0, 120.0) Radius is: 100.0 You will be asked to specify a point. First enter x, then enter y. Please enter x now: 110 Please enter y now: 120 Congratulations. frilled.cs.indiana.edu%java Four Welcome. Circle created. Center is at: (110.0, 120.0) Radius is: 100.0 You will be asked to specify a point. First enter x, then enter y. Please enter x now: -30 Please enter y now: 120 You missed. frilled.cs.indiana.edu%java Four Welcome. Circle created. Center is at: (110.0, 120.0) Radius is: 100.0 You will be asked to specify a point. First enter x, then enter y. Please enter x now: 170.98 Please enter y now: 190.05 Congratulations. frilled.cs.indiana.edu%```

 5. Write a program (called `Five`) that asks the user to specify the radii of two circles. The first circle has center (100, 200) and the second circle has center (200, 100). Check to see if the circles intersect. If they intersect, then display a message "Circles intersect." Otherwise, display "Circles don't intersect." Hint: Compute the distance between the centers and compare it to the radii. Here's a sample run of such a program: ```frilled.cs.indiana.edu%java Five Welcome. Please specify the radius of the first circle: 10 Great. Now please specify the radius of the second circle: 10 Circles don't intersect. frilled.cs.indiana.edu%java Five Welcome. Please specify the radius of the first circle: 100 Great. Now please specify the radius of the second circle: 100 Circles intersect. frilled.cs.indiana.edu%java Five Welcome. Please specify the radius of the first circle: 70 Great. Now please specify the radius of the second circle: 71.42 Circles don't intersect. frilled.cs.indiana.edu%java Five Welcome. Please specify the radius of the first circle: 70 Great. Now please specify the radius of the second circle: 71.43 Circles intersect. frilled.cs.indiana.edu%java Five Welcome. Please specify the radius of the first circle: 140 Great. Now please specify the radius of the second circle: 1.414299 Circles don't intersect. frilled.cs.indiana.edu%java Five Welcome. Please specify the radius of the first circle: 140 Great. Now please specify the radius of the second circle: 1.4299 Circles intersect. frilled.cs.indiana.edu%```

 6. Write a program (called `Six`) that prints the question Do you want to continue? and reads the user input. If the user input is any of the following: Y Yes OK Sure Why not? print out OK If the user input is N No then print out Terminating Otherwise, print Bad input The case of the user input should not matter. For example, y yes are also valid inputs. Hint: Convert the user input to lowercase and then compare. Here's a sample run of such a program: ```frilled.cs.indiana.edu%java Six Do you want to continue? Y OK frilled.cs.indiana.edu%java Six Do you want to continue? Yes OK frilled.cs.indiana.edu%java Six Do you want to continue? OK OK frilled.cs.indiana.edu%java Six Do you want to continue? suRe OK frilled.cs.indiana.edu%java Six Do you want to continue? Sure OK frilled.cs.indiana.edu%java Six Do you want to continue? whY nOt? OK frilled.cs.indiana.edu%java Six Do you want to continue? why not ? Bad input frilled.cs.indiana.edu%java Six Do you want to continue? N Terminating frilled.cs.indiana.edu%java Six Do you want to continue? NO Terminating frilled.cs.indiana.edu%java Six Do you want to continue? nO Terminating frilled.cs.indiana.edu%java Six Do you want to continue? No! Bad input frilled.cs.indiana.edu%```

 7. Write a program (called `Seven`) that translates a letter grade into a number grade. Letter grades are `A`, `B`, `C`, `D`, `F` possibly followed by `+` or `-`. Their numeric values are 4, 3, 2, 1, and 0. There is no `F+` or `F-`. A `+` increases the numeric value by 0.3, a `-` decreases it by 0.3. However an `A+` has a value of 4.0. Here's a sample run of such a program: ```frilled.cs.indiana.edu%java Seven Enter a letter grade: A+ The numeric value is: 4.0 frilled.cs.indiana.edu%java Seven Enter a letter grade: A + Bad input. frilled.cs.indiana.edu%java Seven Enter a letter grade: U- Bad input. frilled.cs.indiana.edu%java Seven Enter a letter grade: B- The numeric value is: 2.7 frilled.cs.indiana.edu%java Seven Enter a letter grade: C The numeric value is: 2.0 frilled.cs.indiana.edu%java Seven Enter a letter grade: F The numeric value is: 0.0 frilled.cs.indiana.edu%java Seven Enter a letter grade: D- The numeric value is: 0.7 frilled.cs.indiana.edu%java Seven Enter a letter grade: -- Bad input. frilled.cs.indiana.edu%```

 8. Write a program (called `Eight`) that translates a number between 0 and 4 into the closest letter grade. For example, the number 2.8 (which might have been the average of several grades) would be converted to `B-`. Break ties in favor of the better grade; for example 2.85 should be a `B`. Here's a sample run of such a program: ```frilled.cs.indiana.edu%java Eight Enter numeric score then press Enter : 3.85 A frilled.cs.indiana.edu%java Eight Enter numeric score then press Enter : 3.84 A- frilled.cs.indiana.edu%java Eight Enter numeric score then press Enter : 3.5 A- frilled.cs.indiana.edu%java Eight Enter numeric score then press Enter : 3.49 B+ frilled.cs.indiana.edu%java Eight Enter numeric score then press Enter : 3.1 B frilled.cs.indiana.edu%java Eight Enter numeric score then press Enter : 10 A+ frilled.cs.indiana.edu%java Eight Enter numeric score then press Enter : -2 frilled.cs.indiana.edu%java Eight Enter numeric score then press Enter : -0.5 frilled.cs.indiana.edu%```

 9. Write a program (called `Nine`) that reads in three strings and sorts them lexicographically. Here's a sample run of such a program: ```frilled.cs.indiana.edu%java Nine Enter three strings: Alpha Beta Gamma Alpha Beta Gamma frilled.cs.indiana.edu%java Nine Enter three strings: Alpha Gamma Beta Alpha Beta Gamma frilled.cs.indiana.edu%java Nine Enter three strings: Username User Use Use User Username frilled.cs.indiana.edu%java Nine Enter three strings: Alpha Alpha Alpha Alpha Alpha Alpha frilled.cs.indiana.edu%java Nine Enter three strings: Gamma gamma gama Gamma gama gamma frilled.cs.indiana.edu%java Nine Enter three strings: 10 1 2 1 10 2 frilled.cs.indiana.edu%```

 10. A year with 366 days is called a leap year. A year is a leap year if it is divisible by 4 (for example, the year 1980), except it is not a leap year if it is divisible by 100 (for example, the year 1900); however, it is a leap year if it is divisible by 400 (for example, the year 2000). There were no exceptions before the introduction of the Gregorian calendar on October 15, 1582 (for example, the year 1500 was a leap year). Write a program (called `Ten`) that asks the user for a year and computes whether that year is a leap year or not. Here's a sample run of such a program: ```frilled.cs.indiana.edu%java Ten Please enter the year then press Enter : 1500 Leap year: 1500 frilled.cs.indiana.edu%java Ten Please enter the year then press Enter : 1900 1900 not a leap year! frilled.cs.indiana.edu%java Ten Please enter the year then press Enter : 1996 Leap year: 1996 frilled.cs.indiana.edu%java Ten Please enter the year then press Enter : 1997 1997 not a leap year! frilled.cs.indiana.edu%java Ten Please enter the year then press Enter : 2000 Leap year: 2000 frilled.cs.indiana.edu%```

 11. Write a program (called `Eleven`) that asks the user to enter a month 1 = January 2 = February ... and so on and then prints the number of days of the month. For February, print `28 or 29 days` Here's a sample run of such a program: ```frilled.cs.indiana.edu%java Eleven Enter a month : 1 31 days frilled.cs.indiana.edu%java Eleven Enter a month : 2 28 or 29 days frilled.cs.indiana.edu%java Eleven Enter a month : 3 31 days frilled.cs.indiana.edu%java Eleven Enter a month : 4 30 days frilled.cs.indiana.edu%java Eleven Enter a month : 5 31 days frilled.cs.indiana.edu%java Eleven Enter a month : 12 31 days frilled.cs.indiana.edu%java Eleven Enter a month : 13 Bad input frilled.cs.indiana.edu%java Eleven Enter a month : 0 Bad input frilled.cs.indiana.edu%java Eleven Enter a month : 1.2 Exception in thread "main" java.lang.NumberFormatException: 1.2 at java.lang.Integer.parseInt(Integer.java:418) at java.lang.Integer.parseInt(Integer.java:458) at ConsoleReader.readInt(Eleven.java:58) at Eleven.main(Eleven.java:7) frilled.cs.indiana.edu%```

 12. Write a program (called `Twelve`) that reads in two floating-point numbers and tests BOTH whether they are the same up to two decimal places, and whether they are within 0.01 of each other Here's a sample run of such a program: ```frilled.cs.indiana.edu%java Twelve Comparing floating-point numbers. Enter the first number : 1.3456 Enter the second number: 1.3402 1.3456 and 1.3402 are the same up to two decimal places. 1.3456 and 1.3402 are within 0.01 of one another. Thanks for asking. frilled.cs.indiana.edu%java Twelve Comparing floating-point numbers. Enter the first number : 2.003 Enter the second number: 1.998 2.003 and 1.998 are NOT the same up to two decimal places. 2.003 and 1.998 are within 0.01 of one another. Thanks for asking. frilled.cs.indiana.edu%java Twelve Comparing floating-point numbers. Enter the first number : 1.998 Enter the second number: 1.990 1.998 and 1.99 are the same up to two decimal places. 1.998 and 1.99 are within 0.01 of one another. Thanks for asking. frilled.cs.indiana.edu%java Twelve Comparing floating-point numbers. Enter the first number : 1.0000001 Enter the second number: 0.9999999 1.0000001 and 0.9999999 are NOT the same up to two decimal places. 1.0000001 and 0.9999999 are within 0.01 of one another. Thanks for asking. frilled.cs.indiana.edu%```

 13. Enhance the `BankAccount` class by rejecting negative amounts in the `deposit` and `withdraw` methods rejecting withdrawals that would result in a negative balance Write a program (called `Thirteen`) that illustrates the behaviour of your new `BankAccount`. Here's a sample run of such a program: ```frilled.cs.indiana.edu%java Thirteen Hello, and welcome to JavaOne Bank. An account will be created for you. What will the initial balance be? Type it now: 20 The current balance in your account is: 20.0 You now want to make a deposit. How much? Type the amount here: 30 The current balance in your account is: 50.0 You now want to make a withdrawal. How much? Type it now: 100 Sorry, you cannot do that. The current balance in your account is: 50.0 Thanks for using class BankAccount. Good-bye! frilled.cs.indiana.edu%java Thirteen Hello, and welcome to JavaOne Bank. An account will be created for you. What will the initial balance be? Type it now: -20 The current balance in your account is: -20.0 You now want to make a deposit. How much? Type the amount here: 10 The current balance in your account is: -10.0 You now want to make a withdrawal. How much? Type it now: 10 Sorry, you cannot do that. The current balance in your account is: -10.0 Thanks for using class BankAccount. Good-bye! frilled.cs.indiana.edu%java Thirteen Hello, and welcome to JavaOne Bank. An account will be created for you. What will the initial balance be? Type it now: -30 The current balance in your account is: -30.0 You now want to make a deposit. How much? Type the amount here: -20 Sorry, you cannot do that. The current balance in your account is: -30.0 You now want to make a withdrawal. How much? Type it now: -40 The current balance in your account is: 10.0 Thanks for using class BankAccount. Good-bye! frilled.cs.indiana.edu%``` Notice that you are free to allow negative initial balances (resembling a loan) but the two methods that implement deposit and withdraw should behave as stated in the text of the problem (rejecting negative arguments and rejecting operations that result in a negative balance other than the initial creation of the account). If you want you can disallow initial negative balances as well.

 14. Write a program that reads in the name and hourly wage of an employee. Then ask how many hours the employee worked in the past week. Be sure to accept fractional hours. Compute the pay. Any overtime work (over 40 hours per week) is paid at 150 percent of the regular wage. Print a paycheck for the employee. Here's a sample run of such a program: ```frilled.cs.indiana.edu%java Fourteen Please enter employee's name then press Enter : Larry Bird Please enter hourly wage then press Enter : 12.50 Please enter hours worked then press Enter: 10 Paycheck for employee Larry Bird Hours worked: 10.0 Hourly wage: 12.5 Total payment: 125.0 frilled.cs.indiana.edu%java Fourteen Please enter employee's name then press Enter : Michael Jordan Please enter hourly wage then press Enter : 10 Please enter hours worked then press Enter: 50 Paycheck for employee Michael Jordan Hours worked: 50.0 Hourly wage: 10.0 Overtime hours: 10.0 Overtime hourly wage: 15.0 Total payment: 550.0 frilled.cs.indiana.edu%java Fourteen Please enter employee's name then press Enter : Dennis Rodman Please enter hourly wage then press Enter : 2 Please enter hours worked then press Enter: -4 Paycheck for employee Dennis Rodman Hours worked: -4.0 Hourly wage: 2.0 Total payment: -8.0 frilled.cs.indiana.edu%``` Notice it's up to you what you do when the input is out of range. Also, you don't need to use the class `Employee` developed in the previous chapter, the emphasis is here on decisions.

Here are some more questions, followed by some more problems:

1. Explain the difference between an object and a class.

2. Give the Java code for an

• object of class `BankAccount` and

• for an object variable of class `BankAccount`.

3. Explain the differences between an instance variable and a local (or method) variable.

4. Explain the difference between
`new BankAccount(5000); `
and
`BankAccount b;`

5. What are the construction parameters for a `BankAccount` object?

6. What is default construction?

7. Give Java code to construct the following objects:

• A square with center (100, 100) and side length 25
• A bank account with a balance of \$5000.
• A console reader that reads from `System.in`

Write just objects, not object variables.

8. Repeat the preceding exercise, but now

• define object variables that are
• initialized with the required objects.

9. Find the errors in the following statements:
```Rectangle r = (5, 10, 15, 20);

double x = BankAccount(10000).getBalance();

BankAccount b;
b.deposit(10000);
b = new BankAccount(10000);

Purse p = null;

Purse p = new Purse();
```

10. Describe all constructors of the `BankAccount` class. List all methods that can be used to change a `BankAccount` object. List all methods that don't change the `BankAccount` object.

11. What is the value of `b` after the following operations?
```BankAccount b = new BankAccount(10);
b.deposit(5000);
b.withdraw(b.getBalance() / 2); ```

12. If `b1` and `b2` store objects of class `BankAccount`, consider the following instructions.
```b1.deposit(b2.getBalance());
b2.deposit(b1.getBalance());```
Are the balances of `b1` and `b2` now identical? Explain.

13. What is the `this` reference?
These are all questions from the book.

Here are more problems, write programs for them.

In the examples that follow,

• your program's answers are always in `blue`,
• to distinguish them from what you would type as a user.
Remember:
• the resulting programs are elementary,
• and the problems are interesting.

 1. Write a program that asks for an initial balance amount. Create a `BankAccount` object with that amount. Then ask for a deposit amount and a withdrawal amount. Carry out the deposit and withdrawal, then print the remaining balance. Use `ConsoleReader` from Lab Notes Two, and please place your `main` method in the class `BankAccount`. Here's a sample run of such a program: ```frilled.cs.indiana.edu%javac BankAccount.java frilled.cs.indiana.edu%java BankAccount Hello, and welcome to JavaOne Bank. An account will be created for you. What will the initial balance be? Type it now: -40.2 The current balance in your account is: -40.2 You now want to make a deposit. How much? Type the amount here: 120.3 The current balance in your account is: 80.1 You now want to make a withdrawal. How much? Type it now: 34 The current balance in your account is: 46.099999999999994 Thanks for using class BankAccount. Good-bye! frilled.cs.indiana.edu%```

 2. Implement a class `Employee`. An employee has a name (a `String`) and a salary (a `double`). Write a default constructor, a constructor with two parameters (name and salary), and methods to return the name and salary. Write a small program to test your class. Here's a sample run of such a program: ```frilled.cs.indiana.edu%java Employee Creating a new employee. Please type the name: Larry Bird Please specify the salary: 200000 New employee has been created. Name of employee: Larry Bird Salary: 200000.0 Thank you for testing class Employee. frilled.cs.indiana.edu%```

 3. Implement a class `Employee`. An employee has a name (a `String`) and a salary (a `double`). Write a default constructor, a constructor with two parameters (name and salary), and methods to return the name and salary. Test your program, then enhance the class by adding a method `raiseSalary(double byPercent)` that raises the employee's salary by a certain percentage. Here's a sample run of such a program: ```frilled.cs.indiana.edu%java Employee Creating a new employee. Please type the name: Michael Jordan Please specify the salary: 300000 New employee has been created. Name of employee: Michael Jordan Salary: 300000.0 Raising the salary of Michael Jordan By what percentage (e.g., 10, 20, etc.)? 10.5 Name of employee: Michael Jordan Current salary: 331500.0 Thank you for testing class Employee. frilled.cs.indiana.edu%```

 4. Implement a class `Car` with the following properties. A car has a certain fuel efficiency (measured in miles per gallon or liters per km -- pick one) and a certain amount of fuel in the gas tank. The efficiency is specified in the constructor,and the initial fuel level is 0. Supply a method `drive` that simulates driving the car for a certain distance, reducing the fuel level in the gas tank, and methods `getFuelLevel`, returning the current fuel level, and `tank`, to tank up. Sample usage of the class: ```public static void main(String[] args) { Car myBeemer = new Car(29); System.out.println(myBeemer.getFuelLevel()); myBeemer.tank(20); System.out.println(myBeemer.getFuelLevel()); myBeemer.drive(100); System.out.println(myBeemer.getFuelLevel()); } ``` Should produce: ```frilled.cs.indiana.edu%java Car 0.0 20.0 16.551724137931036```

 7. Implement a class `Student`. For the purpose of this exercise, a student has a name and a total quiz score Supply an appropriate constructor and methods `getName()` `addQuiz(int score)` `getTotalScore()`, and `getAverageScore()` To compute the latter, you also need to store the number of quizzes that the student took. Here's a sample run of such a program: ```public static void main(String[] args) { Student a = new Student("Larry"); a.addQuiz(10); a.addQuiz(9); a.addQuiz(8); System.out.println("Grade report for: " + a.getName()); System.out.println("Total score: " + a.getTotalScore()); System.out.println("Average score: " + a.getAverageScore()); }``` Should produce: ```frilled.cs.indiana.edu%java Student Grade report for: Larry Total score: 27.0 Average score: 9.0 frilled.cs.indiana.edu%```

 8. Implement a class `Product`. A product has a name and a price For example `new Product("Toaster", 29.95)` Supply methods `printProduct()` `getPrice()`, and `setPrice()` Write a program that makes two products, prints them, reduces their prices by \$5.00, and then prints them again Here's a sample run of such a program: ```public static void main(String[] args) { Product a = new Product("Toaster", 29.95); Product b = new Product("Phone", 35.55); a.printProduct(); a.setPrice(a.getPrice() - 5.00); a.printProduct(); b.printProduct(); b.setPrice(b.getPrice() - 5.00); b.printProduct(); } ``` Should produce: ```frilled.cs.indiana.edu%java Product Product name: Toaster Product price: 29.95 ------------------------------ Product name: Toaster Product price: 24.95 ------------------------------ Product name: Phone Product price: 35.55 ------------------------------ Product name: Phone Product price: 30.549999999999997 ------------------------------ frilled.cs.indiana.edu%```

 9. Implement a class `Circle` that has methods `getArea()` and `getCircumference()` In the constructor, supply the radius of the circle. Here's a sample run of such a program: ```public static void main(String[] args) { ConsoleReader c = new ConsoleReader(System.in); System.out.println("Please specify the radius of your circle:"); Circle a = new Circle(c.readDouble()); System.out.println("Circle created. "); System.out.println("Area: " + a.getArea()); System.out.println("Circumference: " + a.getCircumference()); System.out.println("Good-bye!"); }``` Should produce: ```frilled.cs.indiana.edu%java Circle Please specify the radius of your circle: 1.0 Circle created. Area: 3.141592653589793 Circumference: 6.283185307179586 Good-bye! frilled.cs.indiana.edu%java Circle Please specify the radius of your circle: 3.14 Circle created. Area: 30.974846927333928 Circumference: 19.729201864543903 Good-bye! frilled.cs.indiana.edu%```

 10. Implement a class `BeerCan` with methods `getSurfaceArea()` and `getVolume()` In the constructor, supply the height and radius of the can. Here's a sample run of such a program: ```public static void main(String[] args) { ConsoleReader c = new ConsoleReader(System.in); System.out.println("Please specify the height of the BeerCan."); double height = c.readDouble(); System.out.println("Please specify the radius of the BeerCan."); double radius = c.readDouble(); BeerCan b = new BeerCan(height, radius); System.out.println("The BeerCan has been created."); System.out.println("Its surface area is: " + b.getSurfaceArea()); System.out.println("Its volume is: " + b.getVolume()); }``` Could produce: ```frilled.cs.indiana.edu%java BeerCan Please specify the height of the BeerCan. 2.5 Please specify the radius of the BeerCan. 1.0 The BeerCan has been created. Its surface area is: 15.707963267948966 Its volume is: 7.853981633974483 frilled.cs.indiana.edu%java BeerCan Please specify the height of the BeerCan. 2 Please specify the radius of the BeerCan. 1 The BeerCan has been created. Its surface area is: 12.566370614359172 Its volume is: 6.283185307179586 frilled.cs.indiana.edu%```

Good luck and don't forget: the harder they seem the more you can learn from them.

But these problems are not difficult. They're just that: good practice.

Here are some more questions to be reviewed:

1. Write the following mathematical expressions in Java.    2. Write the following Java expressions in mathematical notation.
```dm = m * ((Math.sqrt(1 + v / c) / Math.sqrt(1 - v / c)) - 1);

volume = Math.PI * r * r * h;

volume = 4 * Math.PI * Math.pow(r, 3) / 3; ```

3. What is wrong with this version of the quadratic formula?
```x1 = (-b - Math.sqrt(b * b - 4 * a * c)) / 2 * a;

x2 = (-b + Math.sqrt(b * b - 4 * a * c)) / 2 * a;```

4. Give an example of integer overflow. Would the same example work correctly if you used floating-point? Give an example of a floating-point roundoff error. Would the same example work correctly if you used integers? When using integers, you would of course need to switch to a smaller unit, such as cents instead of dollars or milliliters instead of liters.

5. Let `n` be an integer and `x` a floating-point number. Explain the difference between
`n = (int)x;`
and
`n = (int)Math.round(x);`
For what values of `x` do they give the same result? For what values of `x` do they give different results? What happens if `x` is negative?

6. Find at least five syntax errors in the following program.
```public class WarmUpSix {
public static void main(String[] args) {
System.out.print("This program adds two numbers.),
x = 5;
int y = 3.5;
System.out.print("The sum of " + x + " and " + y " is: ");
System.out.println(x + y)
}
}```

7. Find at least three logic errors in the following program.
```public class WarmUpSeven {
public static void main(String[] args) {
int total = 1;
System.out.println("Please enter a number:");
int x1 = Integer.parseInt(console.readLine());
total = total + x1;
System.out.println("Please enter another number:");
int x2 = Integer.parseInt(console.readLine());
total = total + x1;
double average = total / 2;
System.out.println("The average of two numbers is "
+ average);
}
}```

8. Explain the difference between `2`, `2.0`, `"2"`, and `"2.0"`.

9. Explain what each of the following two program segments computes:
```x = 2;

y = x + x;```
and
```s = "2";

t = s + s; ```

10. Uninitialized variables can be a serious problem. Should you always initialize every variable with zero? Explain the advantages and disadvantages of such a strategy.

11. True or false? (`x` is an `int` and `s` is a `String`)

1. `Integer.parseInt("" + x)` is the same as `x`

2. `"" + Integer.parseInt(s)` is the same as `s`

3. `s.substring(0, s.length())` is the same as `s`

12. Give two ways for converting a number to a string. What is the advantage of each of these ways?

13. How do you get the first character of a string? The last character? How do you remove the first character? The last character?

14. How do you get the last digit of a number? The first digit? That is, if `n` is `23456`, how do you find out `2` and `6`? Do not convert the number to a string. Hint: `%`, `Math.log`

15. What is a `final` variable? Can you define a `final` variable without supplying its value?

16. For the purpose of this exercise, for each of the following cases assume:
```double x = 2.5;

double y = -1.5;

int m = 18;

int n = 4;

String s = "Hello";

String t = "World"; ```
What are the values of the following expressions?

1. `x + n * y - (x + n) * y`

2. `m / n + m % n`

3. `5 * x - n / 5`

4. `Math.sqrt(Math.sqrt(n))`

5. `(int)Math.round(x)`

6. `(int)Math.round(x) + (int)Math.round(y)`

7. `s + t`

8. `s + n`

9. `1 - (1 - (1 - (1 - (1 - n))))`

10. `s.substring(1, 3)`

11. `s.length() + t.length()`

Some advice, at the end of this document:

• Please, try think about these problems, and only then look up the answers.

• You have all the answers, so there's no pressure.

• The emphasis is on learning.

• So, try to solve them on your own first.

• Then, please, make sure you check the solutions.

(Note: solutions for these problems have already been posted.)

Try to solve these problems to practice some of the things you learned this week. In the examples that follow, your program's answers are always in `blue`, to distinguish them from what you would type as a user. Remember: the resulting programs are elementary, and the problems are interesting.

These problems are from your book.

 1. Write a program that displays the squares, cubes, and fourth powers of the numbers 1-5. Here's a sample run of such a program: ```frilled.cs.indiana.edu%java One First five powers of 1: 1 1 1 1 1 First five powers of 2: 2 4 8 16 32 First five powers of 3: 3 9 27 81 243 First five powers of 4: 4 16 64 256 1024 First five powers of 5: 5 25 125 625 3125 frilled.cs.indiana.edu%```

 2. Write a program that prompts the user for two integers and then prints The sum The difference The product The average The distance (absolute value of the difference) The maximum (the larger of the two ) The minimum (the smaller of the two) Here's a sample run with your program: ```frilled.cs.indiana.edu%java Two Please enter your first integer number, then press Enter. 3 Please enter your second integer number, then press Enter. 6 3 + 6 = 9 3 - 6 = -3 3 * 6 = 18 avg(3, 6) = 4.5 dist(3, 6) = 3 max(3, 6) = 6 min(3, 6) = 3 frilled.cs.indiana.edu%```

 3. Write a program that prompts the user for a measurement in meters and then converts it into miles, feet and inches. Here's a sample run with your program: ```frilled.cs.indiana.edu%java Three Please enter the measurement in meters: 100 Your original measurement of 100.0 meters has been converted. 0 miles, 328 feet, and 1.0078719999998889 inches. frilled.cs.indiana.edu%java Three Please enter the measurement in meters: 16000 Your original measurement of 16000.0 meters has been converted. 9 miles, 4983 feet, and 7.1495919999956445 inches. frilled.cs.indiana.edu%```

 4. Write a program that prompts the user for a radius and then prints The area and circumference of the circle with that radius The volume and surface area of the sphere with that radius Here's a sample run with your program: ```whitetip.cs.indiana.edu%java Four Please enter value for radius then hit enter. 100 Thank you. The radius is 100.0 Here are the computed values. Area of the circle: 31415.926535897932 Circumference: 628.3185307179587 Area of a sphere: 125663.70614359173 Volume of sphere: 41887.90204786391 whitetip.cs.indiana.edu%java Four Please enter value for radius then hit enter. 1 Thank you. The radius is 1.0 Here are the computed values. Area of the circle: 3.141592653589793 Circumference: 6.283185307179586 Area of a sphere: 12.566370614359172 Volume of sphere: 4.1887902047863905 whitetip.cs.indiana.edu%```

 5. Write a program that asks the user for the lengths of the sides of a rectangle. Then print The area and perimeter of the rectangle The length of the diagonal (use the Pythagorean theorem) Here's a sample run with your program: ```whitetip.cs.indiana.edu%java Five Please enter the value for the first side. 3 Thanks. Side one is 3.0 Please enter the value for the second side. 4 Thanks. Side two is 4.0 Area is: 12.0 Perimeter is: 14.0 Diagonal is: 5.0 whitetip.cs.indiana.edu%java Five Please enter the value for the first side. 1 Thanks. Side one is 1.0 Please enter the value for the second side. 1 Thanks. Side two is 1.0 Area is: 1.0 Perimeter is: 4.0 Diagonal is: 1.4142135623730951 whitetip.cs.indiana.edu%```

 6. (Giving change) Implement a program that directs a cashier how to give change. The program has two inputs: the amount due and the amount received from the customer. Compute the difference, and compute the dollars, quarters, dimes, nickels, and pennies that the customer should receive in return. Hint: First transform the difference into an integer balance, denominated in pennies. Then compute the whole dollar amount. Subtract it from the balance. Compute the number of quarters needed. Repeat for dimes and nickels. Display the remaining pennies. Here's a sample run with your program: ```frilled.cs.indiana.edu%java Six Type the amount due then press enter. 3.72 Type the amount received then press enter. 5 Give 1.28 in change as follows: 5 quarters 0 dimes 0 nickels 3 cents frilled.cs.indiana.edu%java Six Type the amount due then press enter. 0.08 Type the amount received then press enter. 0.5 Give 0.42 in change as follows: 1 quarters 1 dimes 1 nickels 2 cents frilled.cs.indiana.edu%```

 7. Write a program that asks the user to input The number of gallons The fuel efficiency The price Then print how far the car can go with the gas in the tank and print the cost per 100 miles. Here's a sample run with your program: ```frilled.cs.indiana.edu%java Seven Please enter the number of gallons then press enter. 32 Please enter the fuel efficiency (miles/gallon) then press enter. 16 Please enter the price per gallon, then press enter. 1.54 With the gas in the tank you can go 512.0 miles, at a cost of 9.625 per 100 miles. frilled.cs.indiana.edu%java Seven Please enter the number of gallons then press enter. 2.8 Please enter the fuel efficiency (miles/gallon) then press enter. 18.5 Please enter the price per gallon, then press enter. 1.48 With the gas in the tank you can go 51.8 miles, at a cost of 8.0 per 100 miles. frilled.cs.indiana.edu%```

 8. Write a program that reads a number greater than or equal to 1000 from the user and prints it out with a comma separating the thousands Here's a sample run with your program: ```frilled.cs.indiana.edu%java Eight Please enter an integer >= 1000: 2000 2,000 frilled.cs.indiana.edu%java Eight Please enter an integer >= 1000: 2000000 2000,000 frilled.cs.indiana.edu%java Eight Please enter an integer >= 1000: 2000000000 2000000,000 frilled.cs.indiana.edu%java Eight Please enter an integer >= 1000: -3000 -3,000 frilled.cs.indiana.edu%java Eight Please enter an integer >= 1000: 20 Exception in thread "main" [...] ```

 9. Write a program that reads a number greater than or equal to 1000 from the user, where the user enters a comma in the input. Then print the number without a comma. (Hint: Read the input as a string. Measure the length of the string. Suppose it contains n characters. Then extract substrings consisting of the first n - 4 characters and the last three characters.) Here's a sample run with your program: ```frilled.cs.indiana.edu%java Nine Please enter an integer between 1,000 and 999,999: 123,456 123456 frilled.cs.indiana.edu%java Nine Please enter an integer between 1,000 and 999,999: 1,000 1000 frilled.cs.indiana.edu%java Nine Please enter an integer between 1,000 and 999,999: 1000000,000 1000000000 frilled.cs.indiana.edu%```

 10. (Printing a grid) Write a program that prints the following grid to play tic-tac-toe. ```+--+--+--+ | | | | +--+--+--+ | | | | +--+--+--+ | | | | +--+--+--+``` Of course, you could simply write seven statements of the form `System.out.println("+--+--+--+")` You should do it a smarter way, though. Define string variables to hold two kinds of patterns: a comb-shaped pattern and the bottom line. Print the comb three times and the bottom line once. Here's a sample run with your program: ```frilled.cs.indiana.edu%java Ten +--+--+--+ | | | | +--+--+--+ | | | | +--+--+--+ | | | | +--+--+--+ frilled.cs.indiana.edu%```

 11. Write a program that reads an integer and breaks it into a sequence of individual digits. For example the input 16384 is displayed as `1 6 3 8 4` You may assume that the input has no more than five digits and is not negative. Hint: There are two ways of solving this problem. You can use integer arithmetic and repeatedly divide by 10, or you can convert the number into a string and extract the digits from the string. Here's a sample run with your program: ```frilled.cs.indiana.edu%java Eleven Please enter a number between 0 and 99999: 123 1 2 3 frilled.cs.indiana.edu%java Eleven Please enter a number between 0 and 99999: 0 0 frilled.cs.indiana.edu%java Eleven Please enter a number between 0 and 99999: 83021 8 3 0 2 1 frilled.cs.indiana.edu%java Eleven Please enter a number between 0 and 99999: 123456 2 3 4 5 6 frilled.cs.indiana.edu%```

 12 The following program prints the values of sine and cosine for 0 degrees, 30 degrees, 45 degrees, 60 degrees, and 90 degrees. Rewrite the program for greater clarity by factoring out common code. ```public class Twelve { public static void main(String[] args) { System.out.println("0 degrees: " + Math.sin(0) + " " + Math.cos(0)); System.out.println("30 degrees: " + Math.sin(30 * Math.PI / 180) + " " + Math.cos(30 * Math.PI / 180)); System.out.println("45 degrees: " + Math.sin(45 * Math.PI / 180) + " " + Math.cos(45 * Math.PI / 180)); System.out.println("60 degrees: " + Math.sin(60 * Math.PI / 180) + " " + Math.cos(60 * Math.PI / 180)); System.out.println("90 degrees: " + Math.sin(90 * Math.PI / 180) + " " + Math.cos(90 * Math.PI / 180)); } } ```

 13. Write a program that prints out a message "Hello, my name is Hal!" Then, on a new line, the program should print the message "What is your name?" Next the program should read the user's name and print "Hello, user name. I am glad to meet you." Then, on a new line, the program should print a message "What would you like me to do?" Then it is the user's turn to type in an input. Finally the program should ignore the user input and and print the message "I am sorry, user name. I cannot do that." Here's a sample run with your program: ```frilled.cs.indiana.edu%java Thirteen Hello, my name is Hal! What is your name? Dave Hello, Dave. I am glad to meet you. What would you like me to do? Clean up my room, if you'd like. I am sorry, Dave. I cannot do that. frilled.cs.indiana.edu%java Thirteen Hello, my name is Hal! What is your name? Dave Hello, Dave. I am glad to meet you. What would you like me to do? Get lost. I am sorry, Dave. I cannot do that. frilled.cs.indiana.edu%```

 14. This is somewhat tricky so there are lots of hints in the text. You don't know yet how to program decisions, but it turns out that there is a way to fake them using `substring`. Write a program that asks a user to input The number of gallons of gas in the tank The fuel efficiency in miles per gallon The distance the user wants to travel Then print out `You will make it` or `You will not make it` The trick here is to subtract the desired distance from the number of miles the user can drive. Suppose that the number is `x`. Suppose further that you find a way of setting a value `n` to 1 if `x` >= 0 and to 0 if `x` < 0. Then you can solve your problem: ```String answer = " not "; // note the spaces before and after not System.out.println( "You will" + answer.substring(0, 5 - 4 * n) + // sometimes not! "make it"); ``` Hint: Note that `x + |x|` is 2`x` if `x` >= 0, and 0 if `x` < 0. Then divide by `x`, except that you need to worry about the possibility that `x` is zero so use: ```// compute x, the difference between what you can and what you want double x = efficiency * gallons - distance; // avoid division by zero with this, can you see how? double epsilon = 0.00001; // make n 1 if x >= 0 and 0 otherwise long n = Math.round( ( (x + Math.abs(x) ) * x + epsilon) / ( 2 * x * x + epsilon) ); // why can't n be int? what do I need to do if I want it to be an int? // report the correct answer System.out.println("You will" + answer.substring(0, 5 - 4 * (int)n) + "make it."); // why do I need to convert n from the long it is to an int here? ``` Here's a sample run with your program: ```frilled.cs.indiana.edu%java Fourteen Please enter number of gallons then press enter. 10 Please enter fuel efficiency in miles per gallon. 20 Please enter distance in miles you want to cover. 199 You will make it. frilled.cs.indiana.edu%java Fourteen Please enter number of gallons then press enter. 5 Please enter fuel efficiency in miles per gallon. 20 Please enter distance in miles you want to cover. 101 You will not make it. frilled.cs.indiana.edu%```

 15. Write a program that reads two times in military format (0900, 1730) and prints the number of hours and minutes between the two times. Here is a sample run. User input is in color. ```Please enter the first time: 0900 Please enter the second time: 1730 8 hours 30 minutes``` Extra credit if you can deal with the case that the first time is later than the second time: ```Please enter the first time: 1730 Please enter the second time: 0900 15 hours 30 minutes``` Here's a sample run with your program: ```frilled.cs.indiana.edu%java Fifteen Please enter the first time: 0920 Please enter the second time: 1025 1 hours 5 minutes frilled.cs.indiana.edu%java Fifteen Please enter the first time: 1025 Please enter the second time: 0920 22 hours 55 minutes frilled.cs.indiana.edu%```

 16 Run the following program, and explain the output you get. ```public class Sixteen { public static void main(String[] args) { ConsoleReader console = new ConsoleReader(System.in); int total = 0; System.out.println("Please enter a positive number:"); int x1 = Integer.parseInt(console.readLine()); System.out.println("total = " + total); total = total + 1 / x1; System.out.println("total = " + total); System.out.println("Please enter a positive number:"); int x2 = Integer.parseInt(console.readLine()); total = total + 1 / x2; System.out.println("total = " + total); total = total * x1 * x2 / 2; System.out.println("total = " + total); System.out.println("The average is " + total); } }``` Note the trace messages, which are inserted to show the current contents of the `total` variable. Then fix up the program, run it with the trace messages in place to verify that it works correctly, and remove the trace messages.

 17. Writing large letters. A large letter `H` can be produced like this: ```* * * * ***** * * * *``` It can be declared as a string constant like this: ```public static final String LETTER_H = "* *\n* *\n*****\n* *\n* *\n";``` Do the same for the letters `E`, `L`, and `O`. Then write the message ```H E L L O``` Here's a sample run with your program: ```frilled.cs.indiana.edu%java Seventeen * * * * ***** * * * * ***** * ***** * ***** * * * * ***** * * * * ***** *** * * * * * * *** frilled.cs.indiana.edu%```

 18. Write a program that transforms numbers `1`, `2`, `3`, ..., `12` into the corresponding month names `January`, `February`, `March`, ..., `December` Hint: Make a very long string `"January February March......."` in which you add spaces such that each month name has the same length. Then use `substring` to extract the month you want. Here's a sample run with your program: ```frilled.cs.indiana.edu%java Eighteen Please enter a month number from 1 to 12. 2 February frilled.cs.indiana.edu%java Eighteen Please enter a month number from 1 to 12. 12 December frilled.cs.indiana.edu%java Eighteen Please enter a month number from 1 to 12. 1 January frilled.cs.indiana.edu%java Eighteen Please enter a month number from 1 to 12. 14 Exception in thread "main" [...] frilled.cs.indiana.edu%```

Last updated: Feb 20, 2003 by Adrian German for A201