How many gumballs? How many kids? 80.5 6
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at KeepingMoreKidsQuiet.main(KeepingMoreKidsQuiet.java:12)
I get an InputMismatchException because keyboard.nextInt() expects me to type an int value, and 80.5 isn't an int value.
How many gumballs? How many kids? "80" "6"
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at KeepingMoreKidsQuiet.main(KeepingMoreKidsQuiet.java:12)
I get an InputMismatchException because keyboard.nextInt() expects me to type an int value, and "80", with quotation marks, isn't an int value. (In fact, "80" is a string of characters -- the digit character 8 followed by the digit character 0. More on that in Chapter 18.)
import java.util.Scanner;
class AddingMachine {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
int firstNumber;
int secondNumber;
int sum;
System.out.print("Enter two numbers: ");
firstNumber = keyboard.nextInt();
secondNumber = keyboard.nextInt();
sum = firstNumber + secondNumber;
System.out.print("The sum is ");
System.out.print(sum);
System.out.println(".");
keyboard.close();
}
}
| Welcome to JShell -- Version 9-ea
| For an introduction type: /help intro
jshell> int a = 8
a ==> 8
jshell> int b = 3
b ==> 3
jshell> int c = b / a
c ==> 0
jshell> int d = a / b
d ==> 2
jshell> int e = a % b
e ==> 2
jshell> int f = 5 + e * d - 2
f ==> 7
jshell> /exit
| Goodbye
import java.util.Scanner;
class Anniversaries {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int years;
System.out.print("How many years? ");
years = keyboard.nextInt();
System.out.print("Number of anniversaries: ");
System.out.println(years / 4);
keyboard.close();
}
}
| Welcome to JShell -- Version 9-ea
| For an introduction type: /help intro
jshell> int i = 8
i ==> 8
jshell> i++
$2 ==> 8
jshell> i
i ==> 9
jshell> i
i ==> 9
jshell> i++
$5 ==> 9
jshell> i
i ==> 10
jshell> ++i
$7 ==> 11
jshell> i
i ==> 11
jshell> /exit
| Goodbye