![]() |
Computer Science Department |
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: |
|
Materials: |
Divide0.java BadInput.java |
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 |
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.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.last updated 10/5/11 - nlh