CS 139 Algorithm Development
Lab06B: Intro to Decisions - Handling Bad Input

Objectives

The students will be able to:


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

 


Part 1 - Divide by zero error

  1. Compile Divide0.java and execute it. Use the first operand of 10 and the second operand of 3. What is output?

  2. Execute your program again, this time using 10 and 0 as operands. What error message do you see?

  3. This error is an example of a run-time error. The message tells you what error you had and where it occurred.

  4. 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.

  5. 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.

  6. Compile your program and use the values of 10 and 0. What error message do you see?

  7. Why do you get this message?

  8. Correct this condition using another if/else structure. Recompile your program and test with 10 and 0. What output do you get?

  9. You have two if/else statements that should look similar. What is the conditional expression that you are using in both?

  10. 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

  1. Compile and run BadInput.java. Use the correct expected type of values.

  2. Now, run this program again and enter the value "x" when it asks for the integer value.

  3. What error message do you see?

  4. 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.

  5. 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.

  6. Do the same thing for the second operand.

  7. Why is it better to leave these as two separate if/else statements?

  8. Compile your program. What error message do you get?

  9. 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.

  10. 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.

  11. Compile and test your code using normal input as well as input with bad values (such as character data).

  12. 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.

  1. 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.
  2. 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

  1. 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).

  2. 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).

  3. Strings have two special comparison methods, equals and equalsIgnoreCase, that let us compare String values.

  4. In your first program, Divide0.java, add a section of code to compare Strings as follows:
    1. Declare two String variables (any name is fine).
    2. Create two read statements to fill in the variables from keyboard entry.
    3. 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.
    4. 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".
    5. Test with several different Strings.

  5. Hmmm.....
    1. 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.
    2. Test with two Strings that are identical and print the equals message when using the methods.
    3. 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.)
    4. 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.
    5. What happened, and why?


last updated 10/3/12 - nlh
10/3/12 - rfg