Mixing input types
A program often reads several kinds of values. The recipe is the same every time: read one line with scanner.nextLine(), then convert it to the type you need.
| To get | Write |
|---|---|
a String |
scanner.nextLine() |
an int |
Integer.valueOf(scanner.nextLine()) |
a double |
Double.valueOf(scanner.nextLine()) |
a boolean |
Boolean.valueOf(scanner.nextLine()) |
Each read takes the next line of input, so the order of the reads has to match the order of the input.
Scanner scanner = new Scanner(System.in);
String item = scanner.nextLine();
int count = Integer.valueOf(scanner.nextLine());
double weight = Double.valueOf(scanner.nextLine());
System.out.println(count + " x " + item + ", " + weight + " kg each");
melon
3
1.253 x melon, 1.25 kg each