reset password
Author Message
wcwir
Posts: 75
Posted 14:54 Oct 23, 2019 |

It seems many of you are making the same mistake when in LAB 8. For example:

Why is this bad, given that the program behaves how it is supposed to? Because this program is hard to read and debug. And it is really a mis-use of System.exit() -- in this course you should use it only when you need to end the program early because the user input is invalid. In this case, a digit is valid input (even if it happens to offend the monster.)

How can you fix it? One way is to use the break keyword:

This is better. At least I'm not using System.exit(). Notice that I was able to move the "BYE" statement out of the loop -- it will still run, because break will end the loop but not the whole program. But I still don't really like it. It is still hard to read and debug this code.

What would make it easier to read? If I could tell from the loop-continuation-condition when the loop terminates. As it is, it looks like it is meant to be an infinite loop, and I have to read the whole loop body to find out that it actually terminates when it reads a digit.

Let's write it without the break keyword:

This is fine... Now when I read the code, I can see right away that the loop will end when it encounters a digit. But the program is performing the same check (Character.isDigit(c)) in two places. Also, now I have to give char c some initial value, so the condition can be checked before the program reads any use input.

So here is another way, written using a Boolean flag:

This is my favorite version. You can figure out what the program does and why by reading the code. The code tells you that the monster starts out happy, and that the loop runs as long as it stays happy. To find out what makes the monster unhappy, you can search the loop body for all occurrences of the variable 'happy' and see under what condition it flips to false. If you want to modify the code to make the monster unhappy when it barfs, or when it receives a certain character, you can easily add code to the loop body without touching the loop-continuation-condition.

(BTW: in this example, digits are sentinel values. See more examples of using them in Liang section 5.5.)

Last edited by wcwir at 13:46 Oct 24, 2019.