Spring Semester 2005

Lecture Notes: In which we help with Homework Two.

First I want to be sure everybody knows where the solutions for Homework One can be found.

# Problem Seven (Clock)

If someone gives me a string like this:
`"10:45"`
I would first name the string so I can refer to it later:
```String a;
a = "10:45"```
So now, from `a`, I would be able to extract:
```String hour;
hour = a.substring(0, 2)```
and something similar would give me (as a substring) the number of minutes.

Note that `hour` is not a number. It is a string representing a number.

To obtain numbers from strings I need to use a parsing routine.

Thus, for example, I could get the integer number `10` (from `"10"`)

```int h;
h = Integer.parseInt(hour)```
and in the same fashion we would be able to obtain `45` (from `"45"`)

So we should count now on having defined and initialized `h` and `m`, two `int` variables.

Now we need to simulate ten minutes.

Essentially this means:

```m = m + 1;
m = m + 1;
m = m + 1;
...
m = m + 1; // ten times ```
After each `m = m + 1;` we need to ask if `m` has reached `60` or not.

If `m` has reached `60` we need to reset it to `0` and add one to the counter of hours.

So each increase in `m` might generate an increase in `h` as well.

That's why we also need to detect when `h` becomes `24`.

When that happens we should simply reset the counter for hours (make it zero).

Notice how keeping track of the minutes and hours is similar to keeping score in Problems Four and Five.

So now the structure of your program could be:

(a) define and initialize `h`, `m`;
(b) `m = m + 1;`
(c) if `m` reaches one hour do two things:
1. reset `m` and increment `h` by `1`
2. reset `h` if `h` is now `24`
(d) print the current time of the clock
(e) repeat steps (b), (c) and (d) ten times.
One final note:
Assume `int h = 3, m = 8; // 3:08am, basically`

How do you print `03:08` out of `h` and `m`?

Printing `h + ":" + m` won't work (it gives `3:8`, lacking leading zeros).

So I'd do this to add leading zeros:

```String a = "00" + h;
System.out.println(a.substring(a.length() - 2));```
It's what we did when we padded with blanks and zeroes above and in Homework One.
Other approaches are possible, too. Hope these comments are useful.

# Problem Eight (Fats)

This problem should be easy. Let me review the example posted already.

1. The program asks about the total number of calories. The user enters 200.

2. The program reads that and now asks about the total grams of fat. The user enters 14.

3. Now the program knows that one gram of fat has 9 calories.

4. So the program quickly calculates 9 times 14 = 126 calories from the 14 grams of fat.

5. 126 just calculated is greater than 0.3 times 200 so the food is not low in fat.

(0.3 times 200 is 30 percent of the total number of calories).

In addition to the steps discussed above you need to validate the input.

Thus

• if the doesn't enter a positive value for the total number of calories you report an error and stop.
Likewise
• if the number of calories from fat is not greater than zero you report an error and stop.
And
• if the number of calories from fat is greater than the total number of calories you report an error and stop.
As far as input validation goes a flowchart would greatly help you organize your thoughts.

There are two such examples below.

# Problem Six (Calculate)

First off, we read a `String` and give it a name.

```String a;
a = console.readLine(); ```
Suppose we're working on this input value:
`a = "123";`
Then what the problem wants me to do is to calculate
`1 + 2 + 3`
One can extract the individual characters in two ways:
`a.charAt(0) + a.charAt(1) + a.charAt(2)`
which evaluates to an integer but not the `6` we were hoping for.

Or we could extract substrings:

`a.substring(0, 1) + a.substring(1, 2) + a.substring(2, 3)`
which evaluates to a string just like the one we started from.

Note that

`a.charAt(0) - '0'`
evaluates to `1` (as needed) and
`Integer.parseInt(a.substring(0, 1))`
also evaluates to the `1` that we need.

So using this method throughout you can get the individual values of the constituent digits.

So now the only problem is: what if the string is not 10 characters (digits) long.

1. In that case, perhaps it's bigger: that should generate an error message and the program should stop.

2. If it's smaller we need to pad with `0` (zeroes) like in Homework One.

How would I pad `"123"` with `0` (zeroes)?

I carefully define

`String reserve = "0000000000"; `
which is the largest string of `0`'s I will need in this problem.

• Now I read `a` and I determine its `a.length()` to be `3`.

• So I should get `reserve.substring(0, 7)` and add it to `a`.

• Notice that `7` is `10 - a.length()`.

Once I have an `a` of `"0000000123"` I can refer to its digits one by one.

I only need to use one of the methods described before, to sum up its digits and report the sum.

# Program Nine (Taxes)

This is a simple problem.

1. Read the income. If negative or too big complain and stop.
2. For a valid income determine the percent used in calculating the taxes.
3. Given the percent determine the taxes and report the value.

Determining the percent used in calculating the taxes resembles the conversion in Problem Ten.

So let's look at that problem now. (A flowchart is essential at this stage).

# Problem Ten (Grades)

We all now the following correspondence:
 `A` (`4.0`) `A-` (`3.7`) `B+` (`3.3`) `B` (`3.0`) `B-` (`2.7`) `C+` (`2.3`) `C` (`2.0`) `C-` (`1.7`) `D+` (`1.3`) `D` (`1.0`) `D-` (`0.3`) `F` (`0.0`)
So now if one gives us a value of `3.9` what letter grade is closer to it?

Moreover, how would we go about systematically determining a letter for a score?

A flow chart is what's needed here.

Let's look at an example for the time being:

• User enters `2.85`
• Program says: could this be an `A`?
• The answer is: no, because it's not above `3.85`
• Why `3.85` for an `A`? Can you think of a good reason?
• Notice that `3.85` is equally distant from `4.0` (A) and `3.7` (A-).
• But `!(2.85 >= 3.85)` so the letter won't be an `A`.
• Now we need a mechanism to systematically exhaust all possibilities.
• So one immediately thinks: could it then be an `A-`?
• Well, for an `A-` we'd need to have at least a `3.5` average.
• (You will notice that below `3.5` you'd be closer to `B+`).
• And `!(2.85 >= 3.5)` so we need to keep going (not an `A-`).
• And `!(2.85 >= 3.15)` so we need to keep going (not a `B+` either).
• But `(2.85 >= 2.85)` so the grade is a `B`
Hope this helps.

# Problem Four (Quiz)

Generating the random numbers is explained in the text of the problem.

Truncating or rounding should be easy, just like in Homework One.

Here's how we simulate a pair of dice:

```int d1, d2;
d1 = (int)(Math.random() * 6);
d2 = (int)(Math.random() * 6);```
In your problem you need to generate random integers between `-50` and `50`.

So the program behaves like this:

(a) set up some useful variables: `correct`, `total`, `n1`, `n2`
(b) initialize `correct` and `total` with `0`

(c) generate a new value for `n1`
(d) generate a new value for `n2`
(e) ask the question (what's `n1` plus `n2`?)
(f) read the answer (where, in what variable?)
(g) (in situations like these we realize that we need to define a variable `answer` as well).
(h) if the answer is correct increment the variable `correct`
(i) increment the variable `total`

(j) repeat steps (c)-(i) ten times.

(Report `correct` and `total` every time).

So this is not a difficult problem. Let's move on.

# Problem One (GPA)

A simple flowchart should clarify this problem.

# Problem Two (Divisible)

Just think:
What does `n % 19` give us for any positive `int n;`?

# Problem Three (Songs)

This problem is just like the first one, so a simple flowchart should be enough help.

# Problem Five (PRS)

Assume `user` has the user's score and `comp` has the one for the computer.

```if (user has chosen paper    AND computer has chosen rock     OR
user has chosen rock     AND computer has chosen scissors OR
user has chosen scissors AND computer has chosen paper      ) {
// computer has lost, user has won
increment user by one
} else { // user has lost (computer won) or computer and user tied
if (user has chosen rock     AND computer has chosen paper    OR
user has chosen scissors AND computer has chosen rock     OR
user has chosen paper    AND computer has chosen scissors   ) {
// computer has won, user has lost
increment comp by one
} else { // tie
// nothing happens
}
} ```
I would use integer values of
• `0` for paper,
• `1` for rock, and
• `2` for scissors

This would make it easier for us to generate random choices for the computer.

Of course, when reporting we should convert to strings (using the actual names).

Last updated by Adrian German for A201/A597/I210 on `Mon Feb 7 13:37:08 EST 2005`