Unit 2 ยท Expressions and input
Java is statically typed: every variable has a declared type. Use int for whole numbers, double for measurements, boolean for truth values, and char for one character. A String is an object representing text.
import java.util.Scanner;
public class Average {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("First mark: ");
double first = input.nextDouble();
System.out.print("Second mark: ");
double second = input.nextDouble();
double average = (first + second) / 2.0;
System.out.printf("Average: %.1f%n", average);
}
}Use 2.0, not 2, when you want floating-point division. A cast such as (double) total / count converts before division.
7 / 2 as an int?String capitalized?Mastery task: Build a receipt calculator that reads item price, quantity, and tax rate, then prints subtotal, tax, and total to two decimal places.