In this program, you'll learn to the usage of if else by a given number. This is done by using a if else statement in Java.
Example 1 : If Student marks is grater than equal 60 print "passed" else "failed"
import java.util.Scanner;
public class Grade {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your mark : ");
int m = input.nextInt();
System.out.print("Your result is ");
if (m >= 60 && m <= 100) {
System.out.println("Pass");
} else if (m >= 0 && m <= 59) {
System.out.println("Fail");
} else {
System.out.println("Your marks rang is wrong!");
}
}
}
When you run the program, the output will be:
Enter your mark :
60
Your result is Pass
Enter your mark :
120
Your result is Your marks rang is wrong!
Enter your mark :
50
Your result is Fail
Example 2 : Write a program to work out how much a person pay to cinema ,Assume that the full price is Rs.200.00 ,The program should input the age and decide the following basis; under 5-free; age 5-12-full price; age 55 or over-free; *age limit between 0-100
import java.util.Scanner;
public class Ticket {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int p, a;
p = 200;
System.out.println("Enter your age : ");
a = input.nextInt();
System.out.print("Your ticket price is ");
if (a >= 55 && a <= 100) {
System.out.println("free");
} else if (a >= 13 && a <= 54) {
System.out.println("Rs:" + p);
} else if (a >= 5 && a <= 12) {
System.out.println("Rs:" + p / 2);
} else if (a >= 1 && a <= 11) {
System.out.println("free");
} else System.out.println("your age range is wrong!");
}
}
When you run the program, the output will be:
Enter your age :
100
Your ticket price is free
Enter your age :
25
Your ticket price is Rs:200
Example 3 : Write a program to input three numbers and display them increasing numerical size
import java.util.Scanner;
public class Order {
static public void main(String args[]) {
Scanner input = new Scanner(System.in);
int x, y, z;
System.out.println("enter the value of x : ");
x = input.nextInt();
System.out.println("enter the value of y : ");
y = input.nextInt();
System.out.println("enter the value of z : ");
z = input.nextInt();
System.out.print("Decreasing order of three numbers : ");
if (x > y && y > z) {
System.out.println(x + "," + y + "," + z);
}
if (x > z && z > y) {
System.out.println(x + "," + z + "," + y);
}
if (y > x && x > z) {
System.out.println(y + "," + x + "," + z);
}
if (y > z && z > x) {
System.out.println(y + "," + z + "," + x);
}
if (z > y && y > x) {
System.out.println(z + "," + y + "," + x);
}
if (z > x && x > y) {
System.out.println(z + "," + x + "," + y);
}
}
}
When you run the program, the output will be:
enter the value of x :
5
enter the value of y :
1
enter the value of z :
56
Decreasing order of three numbers : 56,5,1