CS 139
Algorithm Development
Lab06B: Intro to Decisions - Handling Bad Input
Objectives
The students will be able to:
- use a java if/else
statement appropriately to avoid runtime errors.
Background
There are a number of conditions that can cause a program to
fail. When we can anticipate such conditions, we can use structures
such as conditional statements to prevent those conditions causing a
run-time error or invalid results.
We will be using the Scanner methods hasNextInt(), and
hasNextDouble() to condition our reading of the input.
New Terms
- Runtime Error
- An error which results in the program failing during execution
- Stack Trace
- A list of method calls that are in the "stack" at the time the
program failed
- Scanner class hasNextInt() and next() methods
- Methods that return a boolean value: true if
the next token matches the expected input, false if not
Instructions
- Create a folder named lab06a in which to store your programs.
It will be most convenient if this folder resides on your
desktop or in your home directory.
- Download the following files into this folder:
- Put your names into each of the three files (either one
partner or both if both worked on it)
- Follow the detailed directions below.
- At the end of the lab, upload the three files to Blackboard
- Divide0.java
- BadInput.java
- Worksheet.txt
Part 1 - Divide by zero error
- Compile Divide0.java and execute it. Use the first operand of
10 and the second operand of 3. What is
output?
- Execute your program again, this time using 10 and 0 as
operands. What error message do you see?
- This error is an example of a run-time error. The message
tells you what error you had and where it occurred.
- To prevent this error, we can use an if else structure to
carry out the division only if the divisor is not 0. We can use
a default value if we try to divide by zero.
- In your program create an if statement that will test
the divisor for zero before carrying out the division operation.
If the divisor is zero, print a message("Cannot divide by
zero"). If the divisor is not zero, carry out the division as is
currently displayed. You should only condition (place inside the
if statement) the division operation.
- Compile your program and use the values of 10 and 0. What error message do you see?
- Why do you get this message?
- Correct this condition using another if/else structure.
Recompile your program and test with 10 and 0. What output do you get?
- You have two if/else statements that should look similar. What is the conditional expression that you
are using in both?
- When you have two statements that are conditioned by the same
expression, you can combine those if/else statements into one
with a block of statements. Combine these two if/else
conditions. Compile and execute your program. You need print
only one error message for the divide by zero condition. Copy and paste your if/else structure in the
appropriate question on the worksheet.
Part 2 - Bad input values - the "has" methods
- Compile and run BadInput.java.
Use the correct expected type of values.
- Now, run this program again and enter the value "x" when it
asks for the integer value.
- What error message do you see?
- We can end the program "elegantly" rather than crashing as
before. The Scanner method
hasNextInt()
returns
a boolean value. If the input stream does not contain an integer
as the next token, the return value is false
.
If the input stream contains an integer as the next token, the
return value is true
. We can use this
method to read a value only when it is of the correct type.
- Add an if/else statement around your first read statement. The
condition should use the
Scanner
object's hasNextInt()
method. If the condition is
true, read the value using the normal nextInt()
method. If the condition is false, read the value using the next()
method and print the error message
"Bad value "
followed by the value that
was entered.
- Do the same thing for the second operand.
- Why is it better to leave these as two
separate if/else statements?
- Compile your program. What error
message do you get?
- This error is caused because you set the value of the operands
only in the case where there is a good value. There are two ways
to handle a bad value. One is to simply skip all remaining
statements and exit the program. Another is to use a default
value.
- We will set the operands using a constant in the Integer
class. The Integer class has services that we can use with
integer data. It also has a value, Integer.MAX_VALUE
which is the larges number that and integer variable can hold.
In your code, set either operand with a bad value to Integer.MAX_VALUE.
- Compile and test your code using normal input as well as input
with bad values (such as character data).
- Turn this program in with your completed worksheet.
Part 3 - CodingBat
CodingBat is a web site that has practice programming problems. These are set up as individual methods. See the About page for more information.
- Go to www.codingbat.com. Create an account (upper right hand part of the window). Log in and then go to Prefs. Fill in your name and then "Share" your account out to your instructor by putting their e-mail address in the Share box.
- In Warm-Ups-1 (Java side), do problems sumDoubleH and makes10. Keep working on the problem until you pass all of the tests.
We will use CodingBat for additional labs, but you are also free to try any and all of the practice problems if you wish.
Part 4 - Optional - Comparing Strings
- In Part 1, you compared the value of an operand with 0 to
determine whether or not you should carry out the division
operations. Integers have very straightforward comparisons. This
is generally true of most of the primitive types. What are the 8
primitive types? (Note: not in red and not required to be
answered).
- Strings are objects in Java. That means that if we use the == symbol to compare Strings, we might get
some unintended consequences...in most cases the answer will be
false even if the two Strings have the same symbols in the same
order (they are equivalent values).
- Strings have two special comparison methods, equals and equalsIgnoreCase,
that let us compare String values.
- In your first program, Divide0.java,
add a section of code to compare Strings as follows:
- Declare two String variables (any name is fine).
- Create two read statements to fill in the variables from
keyboard entry.
- Output a statement that will print the message "%s is equal to %s" or "%s is not equal to
%s" based on whether or not the two are exactly
equal. The %ses will be replaced by the two String
variables.
- Output a second statement that will print the message "%s is equal to %s if we ignore case" or
"%s is not equal to %s even if we ignore
case".
- Test with several different Strings.
- Hmmm.....
- Now add one more statement to compare the strings, this
time using the == symbol instead
of the .equals() method call. Print the same message as
4.4.c above.
- Test with two Strings that are identical and print the
equals message when using the methods.
- Why does this comparison fail? (Thought question. See if
you can figure it out given the fact that a Strings are
reference types and that the ==
method compares references.)
- Finally, assign the value of one String to the other. Now
test the Strings for equality using the ==
symbol and print out an appropriate message. Test.
- What happened, and why?
last updated 10/3/12 - nlh
10/3/12 - rfg