Now let’s see an example that’s a little more useful. Although most of the world has adopted the metric system for weights and measures, some countries are stuck with English units. For example, when talking with friends in Europe about the weather, people in the United States might have to convert from Celsius to Fahrenheit and back. Or they might want to convert height in inches to centimeters.
We can write a program to help. We’ll use a
Scanner to input a measurement in inches, convert to centimeters, and then display the results. The following lines declare the variables and create the
int inch; double cm; Scanner in = new Scanner(System.in);
The next step is to prompt the user for the input. We’ll use
println so they can enter the input on the same line as the prompt. And we’ll use the
nextInt, which reads input from the keyboard and converts it to an integer:
System.out.print("How many inches? "); inch = in.nextInt();
Next we multiply the number of inches by 2.54, since that’s how many centimeters there are per inch, and display the results:
cm = inch * 2.54; System.out.print(inch + " in = "); System.out.println(cm + " cm");
This code works correctly, but it has a minor problem. If another programmer reads this code, they might wonder where 2.54 comes from. For the benefit of others (and yourself in the future), it would be better to assign this value to a variable with a meaningful name. We’ll demonstrate in the next section.