Java Reference
In-Depth Information
If a user types something that isn't an integer when you call
nextInt
, such as
XYZZY
, the
Scanner
object generates an exception. Recall from the section on
String
objects that exceptions are runtime errors that halt program execution. In this
case, you'll see runtime error output such as the following:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Example.main(Example.java:13)
You will see in a later chapter how to test for user errors. In the meantime, we will
assume that the user provides appropriate input.
Using the
Scanner
class, we can write a complete interactive program that performs a
useful computation for the user. If you ever find yourself buying a house, you'll want
to know what your monthly mortgage payment is going to be. The following is a com-
plete program that asks for information about a loan and prints the monthly payment:
1 // This program prompts for information about a loan and
2 // computes the monthly mortgage payment.
3
4
import
java.util.*; // for Scanner
5
6
public class
Mortgage {
7
public static void
main(String[] args) {
8 Scanner console =
new
Scanner(System.in);
9
10 // obtain values
11 System.out.println("This program computes monthly " +
12 "mortgage payments.");
13 System.out.print("loan amount : ");
14
double
loan = console.nextDouble();
15 System.out.print("number of years : ");
16
int
years = console.nextInt();
17 System.out.print("interest rate : ");
18
double
rate = console.nextDouble();
19 System.out.println();
20
21 // compute result and report
22
int
n = 12 * years;
23
double
c = rate / 12.0 / 100.0;
Search WWH ::
Custom Search