Examples
This section includes three examples of full programs using conditional statements.
Example 1: max heart rate calculator
There are many different formulas for estimating a person’s maximum heart rate using their age and biological sex. Here is one such estimation:
For men: 220 – age
For women: 206 – 88% of age(Every such formula is only an estimation, and may or may not be accurate for a particular person.) Below is a complete program that asks for a user’s age and sex, and then prints their maximum heart rate according to the estimation above.
import java.util.*;
public class Example1
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = s.nextInt();
System.out.print("Enter (m)ale or (f)emale: ");
char mOrF = (s.nextLine()).charAt(0);
if (mOrF == 'm' || mOrF == 'M')
{
int max = 220-age;
System.out.printf("Max HR: %d%n", max);
}
else if (mOrF == 'f' || mOrF == 'F')
{
double maxF = 206 – 0.88*age;
System.out.printf("Max HR: %.2f%n" + maxF);
}
else
{
System.out.println("Invalid input");
}
}
}Example 2: minimum of two numbers
In this example, we will get two numbers as input from the user, and we will print out whichever number is smaller. In the case of a tie, it doesn’t matter which number we print.
import java.util.*;
public class Example2
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter the first number: ");
int num1 = s.nextInt();
System.out.print("Enter the second number: ");
int num2 = s.nextInt();
if (num1 < num2)
{
System.out.println(num1);
}
else
{
System.out.println(num2);
}
}
}Example 3: temperature converter
In this example, we will ask the user for a temperature and the system being used (Fahrenheit or Celsius). We will then print the equivalent temperature in the other system (i.e., if we start with Fahrenheit then we will convert to Celsius, and vice versa). Here are the formulas that are used to convert between the two (C is Celsius and F is Fahrenheit):
C = (5/9)*(F-32)
F = (9/5)*C+32Here is our full program:
import java.util.*;
public class Example3
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter the temperature: ");
double temp = s.nextDouble();
System.out.print("Enter (f)ahrenheit or (c)elsius: ");
char system = (s.nextLine()).charAt(0);
double newTemp;
if (system == 'f' || system == 'F')
{
newTemp = (5.0/9.0)*(temp-32);
}
//we are assuming that the user typed either f or c
else
{
newTemp = (9.0/5.0)*temp + 32;
}
System.out.printf("Converted: %.2f%n", newTemp);
}
}