Step 5 of 6
A small calculator
Time to put the operators together. A calculator program reads two numbers and prints one line per operation:
Scanner scanner = new Scanner(System.in);
int a = Integer.valueOf(scanner.nextLine());
int b = Integer.valueOf(scanner.nextLine());
System.out.println(a + " + " + b + " = " + (a + b));
System.out.println(a + " / " + b + " = " + ((double) a / b));
7
27 + 2 = 9
7 / 2 = 3.5Two details make it right:
- Each calculation is in parentheses, so it happens before the joining.
- The division casts to
double, so7 / 2shows3.5and not3.