Read, calculate, print
Many programs have the same three parts, whatever they're about:
- Read the input into variables.
- Calculate the result from them.
- Print the result.
Here the input is a temperature in Celsius, and the result is the same temperature in Fahrenheit:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 1. Read
int celsius = Integer.valueOf(scanner.nextLine());
// 2. Calculate
double fahrenheit = celsius * 9 / 5.0 + 32;
// 3. Print
System.out.println(celsius + " C is " + fahrenheit + " F");
}
}
2525 C is 77.0 FWhen a new problem looks hard, start by naming the three parts: what does the program get, what does it work out, and what does it show? Each part is often just a line or two.
Keeping the calculation in its own variable (fahrenheit) makes the print line short and gives the result a name.