Step 5 of 6
Reading doubles and booleans
Decimal numbers and true-or-false answers are read the same way: read a line, then convert it.
Double.valueOf(text)turns text like2.5or-0.75into adouble.Boolean.valueOf(text)givestruewhen the text istruein any mix of capitals (TRUE,True), andfalsefor anything else.
Scanner scanner = new Scanner(System.in);
double height = Double.valueOf(scanner.nextLine());
boolean ready = Boolean.valueOf(scanner.nextLine());
System.out.println("Height: " + height);
System.out.println("Ready: " + ready);
2
yesHeight: 2.0
Ready: falseTwo things in that output are worth a second look:
- The input was
2, but the program prints2.0. Adoubleis always printed with its decimal part. - The input was
yes, which isn'ttrue, so the boolean isfalse.