Java If-Else

Lets understand java’s if else programs which will helpĀ  you understand if else in java

1)Java program to check whether you are eligble for voting or not.

public class checkAge

{

public static void main(String arg[])

{

Scanner sc = new Scanner(System.in);

int age=sc.nextInt(); //Taking input from the user

if(age>=18)

{System.out.println(“You are elgible for voting in India”);}

else

{System.out.println(“You are not eligble”);}

}

}

Here if else so easy as you can see.

2)If -else if ladder

Java program to

Given an integer n perform the following conditional actions:

  • If is odd, print Weird
  • If is even and in the inclusive range of 2 to 5 , print Not Weird
  • If is even and in the inclusive range of 6 to 20 , print Weird
  • If is even and greater than 20 , print Not Weird

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
String ans=””;
if(n%2==1){
ans = “Weird”;
}
else {
if(n>=2 && n<=5) { ans= “Not Weird”; } else if(n>=6 && n<=20)
{
ans=”Weird”;
}
else
{
ans =”Not Weird”;
}
//Complete the code

}
System.out.println(ans);

}
}

Feel free to comment to you have doubt regarding the program.

Advertisements