JamesMadisonUniversity

Computer Science Department


CS 139 Lab: An introduction to conditionals in Java


Objectives:

After this lab, 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.
Stack Trace
The list of method calls in the "stack" when the program failed.
Scanner class hasNextInt() and next() methods
Methods which return a boolean value, true if the next token matches the expected input, false if not.

Materials:

Divide0.java
BadInput.java

Worksheet.txt

Turning in your material:

Turn in your work by submitting Divide0.java, BadInput.java, and the worksheet.txt to this Blackboard assignment.
Acknowledgment Author, Nancy Harris

Divide0.java
BadInput.java

Worksheet.txt

Part 1 - Set up your environment

  1. Create a folder for this lab.
  2. Download the two files, Divide0.java and BadInput.java to that folder.
  3. Download the Worksheet.txt file and open it in a text editor.
  4. Put your name into each of these three files.

Part 2 - Divide by zero error

  1. Compile Divide0.java and execute. 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 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 3 - Bad input values - the "has" methods

  1. Compile and run BadInput.java. Use the 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 we did before. The Scanner method hasNextInt()returns a boolean value. In other words, if the input stream does not contain an integer as the next token, the value is false. If the input stream contains an integer as the next token, the value is true. We can use this fact to read a value in only if 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 in the value using the normal nextInt() method. If the condition is false, read in 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 only set the value of the operands if 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 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. And 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 in 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/5/11 - nlh