Examples
We have now seen how to perform operations on variables, and how to get user input. Let’s practice with two complete example programs.
Area of a rectangle
Suppose we want to ask the user for the length and width of a rectangle, and then print out the area of the rectangle.
Here are the steps we will need:
- Declare all the variables for the program. This includes the length, width, and area of the rectangle.
- Set up a
Scannersince we will need user input. - Ask the user to enter the width. Read what was typed into the
widthvariable. - Ask the user to enter the length. Read what was typed into the
lengthvariable. - Assign
areato be thewidthtimes thelength(which is how the area of a rectangle is computed) - Print the area to the screen
Here is the complete program:
import java.util.*;
public class Rectangle
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
int length;
int width;
int area;
System.out.print("Enter the width: ");
width = s.nextInt();
System.out.print("Enter the length: ");
length = s.nextInt();
area = length*width;
System.out.printf("The area is: %d%n", area);
}
}Temperature calculator
Next, suppose we want to ask the user for a temperature in Celsius, and then print out the result in Fahrenheit. Here are the steps we will need:
- Declare all the variables for the program. This includes the temperature in Fahrenheit (
f) and the temperature in Celsius (c). - Set up a
Scannersince we will need user input. - Ask the user to enter the temperature in Celsius. Read what was typed into the
cvariable. - Assign
fto be9/5*c + 32(that is the formula for converting from Celsius to Fahrenheit) - Print the temperature in Fahrenheit (
f) to the screen
Here is the complete program:
import java.util.*;
public class Temperature
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
double f;
double c;
System.out.print("Temperature in Celsius: ");
c = s.nextDouble();
f = (9.0/5.0)*c + 32;
System.out.printf("In Fahrenheit: %f%n", f);
}
}Note that we changed the conversion formula to be 9.0/5.0*c + 32 instead of 9/5*c + 32. Can
you think why that would be?
(Remember integer division – if we divide two whole numbers, the decimal portion of the result
is cut off. Since 9 and 5 are both whole numbers, 9/5 is just 1, the whole number portion.
However, 9.0 and 5.0 have decimals, so 9.0/5.0 is 1.8, as we want.)