If-else and switch Programs
- Categories Java, if & switch, if & switch
If- else:
1 . Accept a numbers and check whether the number is divisible by both 2 and 3 or not.
import java.util.Scanner; public class DivisivleBy2And3 { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print("Enter the value of n: "); int n = sc.nextInt(); if(n%2 == 0 && n%3 == 0) System.out.println ("The number "+n+" is divisible by 2 and 3"); else System.out.println ("The number "+n+" is not divisible by 2 and 3"); } }
2 . Check whether the given number is even, odd or zero.
import java.util.Scanner; public class EvenOrOdd { public static void main(String[] args) { int number; Scanner scan = new Scanner(System.in); System.out.print("Enter the number you want to check:"); number = scan.nextInt(); scan.close(); if(number==0) { System.out.println(number+" is zero "); } else if(number%2 ==0) { System.out.println(number+" is even number"); } else { System.out.println(number+" is odd number"); } } }
Write a java program to check and display whether the number has single digit or two digit or more
import java.util.*;
public class DigitNum
{
public static void main(String args[ ])
{
Scanner sc =new Scanner (System.in);
int n,p;
System.out.println("Enter a number");
n=sc .nextInt();
p=Math.abs(n);
if(p>=0 && p<=9)
{
System.out.println("The number has single digit");
}
else if(p>=10 && p<=99)
{
System.out.println("The number has two digits");
}
else
{
System.out.println("The number has more than 2 digits");
}
}
}
3 . Finding largest of three numbers using if-else- if
import java.util.Scanner; public class LargestNum { public static void main(String[] args) { int num1, num2, num3; System.out.print("Enter three number to Compare :"); Scanner sc = new Scanner(System.in); num1 = sc.nextInt(); num2 = sc.nextInt(); num3 = sc.nextInt(); if( num1 >= num2 && num1 >= num3) System.out.println(num1+" is the largest Number"); else if( num2 >= num1 && num2 >= num3) System.out.println(num2+" is the largest Number"); else System.out.println(num3+" is the largest Number"); } }
4 . check whether the input year is leap or not
import java.util.Scanner; public class LeapYear { public static void main(String[] args) { int year; Scanner scan = new Scanner(System.in); System.out.println("Enter any Year:"); year = scan.nextInt(); scan.close(); boolean isLeap = false; if(year % 4 == 0) { if( year % 100 == 0) { if ( year % 400 == 0) isLeap = true; else isLeap = false; } else isLeap = true; } else { isLeap = false; } if(isLeap==true) System.out.println(year + " is a Leap Year."); else System.out.println(year + " is not a Leap Year."); } }
5 . Write a program to enter two unequal numbers. If the first number is greater then display square of the smaller number and cube of the greater number otherwise, vice-versa. If the numbers are equal, display the message “Both the numbers are equal”.
import java.io.*; public class Number1 { public static void main (String args[])throws IOException { InputStreamReader read = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(read); int a,b,sq,cb; System.out.println("Enter two numbers"); a=Integer.parseInt(in.readLine()); b=Integer.parseInt(in.readLine()); if(a!=b) { if(a<b) { sq=a*a; cb=b*b*b; } else { sq=b*b; cb=a*a*a; } System.out.println("The square of smaller number:"+sq); System.out.println("The cube of greater number:"+cb); } else System.out.println("Both the numbers are equal"); } }
6 . Write a program to enter a number. If the number is positive even, display three succeeding even numbers. If the number is negative odd, display three preceding odd numbers otherwise, display the message ‘Number is neither a positive even nor a negative odd’.
Sample Input: -21
Sample Output: -23, -25, -27
Sample Input: 34
Sample Output: 36, 38, 40
Sample Input: 41
Sample Output: The number is neither a positive even nor a negative odd
import java.util.Scanner; public class Number2 { public static void main(String args[]) { Scanner in = new Scanner(System.in); int a; System.out.println("Enter a number"); a= in.nextInt(); if(a>0 && a%2==0) System.out.println("The succeeding numbers are:"+(a+2)+ ","+(a+4)+","+(a+6)); else if(a<0 && a%2!=0) System.out.println("The preceding numbers are:"+(a-2)+ ","+(a-4)+ ","+(a-6)); else System.out.println("The number is neither a positive even nor negative odd"); }
7 . Write a program to enter three numbers and a character. Find and print sum of the numbers if the given character is ‘s’ and product of the numbers if the given character is ‘p’. The program displays alphabet other than ‘s’ or ‘p’ .
import java.io.*; public class Number3 { public static void main (String args[])throws IOException { InputStreamReader read = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(read); int a,b,c,sum=0,pr=1; char ch; System.out.println("Enter three numbers"); a=Integer.parseInt(in.readLine()); b=Integer.parseInt(in.readLine()); c=Integer.parseInt(in.readLine()); System.out.println("Enter 's' for sum and p' for product of three numbere"); ch=(char)in.read(); if(ch=='s') { sum=a+b+c; System.out.println("The sum of three numbers:"+sum); } else if (ch=='p') { pr=a*b*c; System.out.println("The product of three numbers:"+pr); } else System.out.println("Entered an invalid character!!!"); } }
8 . Write a java program to find the square root of given number.
import java.util.Scanner; public class PerfectSquare { static boolean checkPerfectSquare(double x) { // finding the square root of given number double sq = Math.sqrt(x); return ((sq - Math.floor(sq)) == 0); } public static void main(String[] args) { System.out.print("Enter any number:"); Scanner scanner = new Scanner(System.in); double num = scanner.nextDouble(); scanner.close(); if (checkPerfectSquare(num)) System.out.print(num+ " is a perfect square number"); else System.out.print(num+ " is not a perfect square number"); } }
9 . Write a program to input three unequal numbers and display the second smallest number.
Sample Input: 65, 41, 98
Sample Output: 65
import java.util.Scanner; public class SecondSmallestNum { public static void main(String args[]) { Scanner in = new Scanner(System.in); int a,b,c; System.out.println("Enter three numbers"); a= in.nextInt(); b= in.nextInt(); c= in.nextInt(); if(a<b) { if(b<c) System.out.println("The second smallest number:"+b); else System.out.println("The second smallest number:"+c); } if(b<c) { if(c<a) System.out.println("The second smallest number:"+c); else System.out.println("The second smallest number:"+a); if(c<a) { if(a<b) System.out.println("The second smallest number:"+a); else System.out.println("The second smallest number:" +b); } } } }
10 . Check whether given alphabet is vowel or consonant using if..else statement.
Ans.
import java.util.Scanner;
public class vowel
{
public static void main(String[ ] arg)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a character : ");
char ch=sc.next( ).charAt(0);
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u'||ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U')
{
System.out.println("Character "+ch+" is Vowel");
}
else if((ch>='a'&& ch<='z')||(ch>='A'&& ch<='Z'))
System.out.println("Character "+ch+" is Consonant");
else
System.out.println("Not an alphabet");
}
}
11 . Write a program to compute the amount that customer pays for the taxi that he hires based on following conditions:Distance Rate Up to 5 km ₹ 75 For the next 10 km ₹ 15/km For the next 10 km ₹ 10/km More than 25 km ₹ 5/km
Input he customers name, the taxi number and number of kilometers travelled by him.
import java.util.Scanner; public class taxi { public static void main(String args[]) { Scanner in = new Scanner(System.in); System.out.print("Enter Customer name: "); String cusName = in.next(); System.out.print("Enter Taxi Number: "); String taxiNo = in.next(); System.out.print("Enter distance travelled: "); int dist = in.nextInt(); int fare = 0; if (dist <= 5) fare = 75; else if (dist <= 15) fare = 75 + (dist - 5) * 15; else if (dist <= 25) fare = 75 + 75 + (dist - 15) * 10; else fare = 75 + 75 + 80 + (dist - 25) * 5; System.out.println("Customer name: " + cusName); System.out.println("Taxi No: " + taxiNo); System.out.println("Distance covered: " + dist); System.out.println("Amount: " + fare); } }
12 . Write a program to compute the railway fare depending on the criteria as given:
age(in year) | distance (in kms) | fare (in rupees) |
bellow 10 | Bellow 10 Between 10 and 50 Above 50 | 5 20 50 |
Between 10 and 60 | Bellow 10 Between 10 and 50 Above 50 | 10 40 80 |
Above 60 | Bellow 10 Between 10 and 50 Above 50 | 4 15 35 |
import java.util.Scanner; public class railway { public static void main(String args[]) { Scanner sc=new Scanner(System.in); System.out.println("Enter age "); int age = sc.nextInt(); System.out.println("Enter distance to be traveled "); int dis=sc.nextInt(); if(age<=10) { if(dis<=10) System.out.println("fair= 5"); else if(dis<=50) System.out.println("fair= 20"); else if(dis>50) System.out.println("fair= 50"); } if(age>10 && age <=60) { if(dis<=10) System.out.println("fair= 10"); else if(dis<=50) System.out.println("fair= 40"); else if(dis>50) System.out.println("fair= 80"); } else { if(dis<=10) System.out.println("fair= 4"); else if(dis<=50) System.out.println("fair= 15"); else if(dis>50) System.out.println("fair= 35"); } } }
13 . A school is alocattong grade and remarks on the basis of total marks (total of 3 sub of 100 marks) obtained by the student as per the following criteria :Marks obtain Grade allocated Remark on grades 85 to 100 A Excellent 75 to 84 B Distinction 60 to 75 C Good 40 to 60 D Fair less than 40 E Need improvement
write a program to input 3 sub marks and ouput total marks, grade allocatted and remar given.
import java.util.*; public class grade { public static void main(String args[]) { Scanner in = new Scanner(System.in); int sub1; int sub2; int sub3; System.out.println("Enter the marks of 3 sub : "); System.out.println("Enter the First Subject marks "); sub1=in.nextInt(); System.out.println("Enter the Second Subject marks "); sub2=in.nextInt(); System.out.println("Enter the Third Subject marks "); sub3=in.nextInt(); int tot = sub1+sub2+sub3; int avg = tot/3; if(avg>=85 && avg<=100) System.out.println("Total= "+tot+" Grade= A Remark= Excellent "); if(avg>=75 && avg<84) System.out.println("Total= "+tot+" Grade= B Remark= Distinction "); if(avg>=60 && avg<75) System.out.println("Total= "+tot+" Grade= C Remark= Good "); if(avg>=40 && avg<60) System.out.println("Total= "+tot+" Grade= D Remark= Fair "); if(avg<40) System.out.println("Total= "+tot+" Grade= E Remark= Need improvement "); } }
Switch case:
1 . Write a program which calculates marks on basis of given grades in java using switch statement
if Grade A then marks >=80
if Grade B then marks >=60 and less than 80
if Grade C then marks >=40 and less than 60
if Grade F then marks <=40
if any other grade is passed then print invalid grade
import java.util.Scanner; public class Cal_Marks { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter grade from (A, B, C or F) : "); String str = scanner.next(); char grade = str.charAt(0); switch (grade) { case 'A': System.out.println("Grade A - marks >=80"); break; case 'B': System.out.println("Grade B - marks >=60"); break; case 'C': System.out.println("Grade C - marks >=40"); break; case 'F': System.out.println("Grade F - marks <40 FAIL"); break; default : //optional System.out.println("Invalid Grade"); break; //optional } } }
2 . Program to make a calculator using switch case in Java.
import java.util.Scanner; public class Calculator { public static void main(String[] args) { double num1, num2; Scanner scanner = new Scanner(System.in); System.out.print("Enter first number:"); num1 = scanner.nextDouble(); System.out.print("Enter second number:"); num2 = scanner.nextDouble(); System.out.print("Enter an operator (+, -, *, /): "); char operator = scanner.next().charAt(0); scanner.close(); double output; switch(operator) { case '+': output = num1 + num2; break; case '-': output = num1 - num2; break; case '*': output = num1 * num2; break; case '/': output = num1 / num2; break; default: System.out.printf("You have entered wrong operator"); return; } System.out.println(num1+" "+operator+" "+num2+": "+output); } }
3 . Write a program to take input level from user and display the difficulty of game.
import java.util.Scanner; public class Level { public static void main(String[] args) { Scanner sc = new Scanner( System.in ); String levelString=null; int level; System.out.print("Input a level: "); level = sc.nextInt(); switch(level) { case 1: case 2: case 3: case 4: case 5: levelString="Beginner"; break; case 6: case 7: case 8: levelString="Intermediate"; break; case 9: case 10: levelString="Expert"; break; default: levelString="Envalid input"; break; } System.out.println("Your at Level : "+levelString); } }
4 . Write a program to take input day from user and display if the day is week day or weekend.
import java.util.Scanner; public class Weekend { public static void main(String[] args) { int day ; Scanner sc = new Scanner( System.in ); System.out.print("Day number: "); day = sc.nextInt(); String dayType; String dayString; switch (day) { case 1: dayString = "Monday"; break; case 2: dayString = "Tuesday"; break; case 3: dayString = "Wednesday"; break; case 4: dayString = "Thursday"; break; case 5: dayString = "Friday"; break; case 6: dayString = "Saturday"; break; case 7: dayString = "Sunday"; break; default: dayString = "Invalid day"; } switch (day) { // multiple cases without break statements case 1: case 2: case 3: case 4: case 5: dayType = "Weekday"; break; case 6: case 7: dayType = "Weekend"; break; default: dayType = "Invalid daytype"; } System.out.println(dayString + " is a " + dayType); } }
5 . Check whether given alphabet is vowel or consonant using Switch case statement.
import java.util.Scanner;
public class vowel
{
public static void main(String[ ] arg)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a character : ");
char ch=sc.next( ).charAt(0);
switch(ch)
{
case 'a' :
case 'e' :
case 'i' :
case 'o' :
case 'u' :
case 'A' :
case 'E' :
case 'I' :
case 'O' :
case 'U' :
System.out.println("Character "+ch+" is Vowel");
break;
default:
System.out.println("Character "+ch+" is Consonant");
}
}
}
6 . Write a Java Program to Find Number of Days in given Month.
import java.util.Scanner;
public class NumberOfDaysInMonth
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int month;
sc = new Scanner(System.in);
System.out.print(" Please Enter Month Number from 1 to 12 (1 = Jan, and 12 = Dec) : ");
month = sc.nextInt();
switch(month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
System.out.println("\n 31 Days in month "+month);
break;
case 4:
case 6:
case 9:
case 11:
System.out.println(“\n 30 Days in month “+month);
break;
case 2:
System.out.println(“\n Either 28 or 29 Days in month “+month);
break;
default:
System.out.println(“\n Please enter Valid Number between 1 to 12”);
}
}
}
7 . The volume of solids, viz. cuboid, cylinder and cone can be calculated by the formula:
- Volume of a cuboid (v = l*b*h)
- Volume of a cylinder (v = π*r2*h)
- Volume of a cone (v = (1/3)*π*r2*h)
Using a switch case statement, write a program to find the volume of different solids by taking suitable variables and data types.
import java.util.Scanner;
public class volumOf
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println(“1. Volume of cuboid”);
System.out.println(“2. Volume of cylinder”);
System.out.println(“3. Volume of cone”);
System.out.print(“Enter your choice: “);
int choice = in.nextInt();
switch(choice)
{
case 1:
System.out.print(“Enter length: “);
double l = in.nextDouble();
System.out.print(“Enter breadth: “);
double b = in.nextDouble();
System.out.print(“Enter height : “);
double h = in.nextDouble();
double vol = l * b * h;
System.out.println(“Volume of cuboid = ” + vol);
break;
case 2:
System.out.print(“Enter radius : “);
double rCylinder = in.nextDouble();
System.out.print(“Enter height: “);
double hCylinder = in.nextDouble();
double vCylinder = (22 / 7.0) * Math.pow(rCylinder, 2) * hCylinder;
System.out.println(“Volume of cylinder = ” + vCylinder);
break;
case 3:
System.out.print(“Enter radius : “);
double rCone = in.nextDouble();
System.out.print(“Enter height : “);
double hCone = in.nextDouble();
double vCone = (1 / 3.0) * (22 / 7.0) * Math.pow(rCone, 2) * hCone;
System.out.println(“Volume of cone = ” + vCone);
break;
default:
System.out.println(“Wrong choice! Please select from 1 or 2 or 3.”);
}
}
}
If- else + Switch case :
1 . The tax department has announced the new tax rated and deduction as per the following rules :Annual income(in Rs) Tax Rates for Female Tax Rate for Male up to 200000 nil nil 200000 to 300000 10% 12% 300000 to 500000 20% 22% 500000 to 1000000 30% 33%
write a program to input employee id, annual income and gender (F for female and M for male). Compute the income tax to be using above criteria. print employee id, gender and tax amount.
import java.util.Scanner; public class tax { public static void main(String args[]) { double tax=0,it; Scanner sc=new Scanner(System.in); System.out.println("Enter employee id "); String eid = sc.next(); System.out.println("Enter income "); it=sc.nextDouble(); System.out.println("Enter employee gender"); char gender= sc.next().charAt(0); switch (gender){ case 'M': if(it<=200000) tax=0; else if(it<=300000) tax=0.12*(it-200000); else if(it<=500000) tax=(0.22*(it-300000))+(0.1*100000); else if(it<=1000000) tax=(0.33*(it-500000))+(0.2*200000)+(0.1*100000); else tax=(0.4*(it-1000000))+(0.3*500000)+(0.2*200000)+(0.1*100000); System.out.println("Employee id: "+eid); System.out.println("Employee gender : "+gender); System.out.println("Income tax amount is "+tax); break; case 'F': if(it<=200000) tax=0; else if(it<=300000) tax=0.1*(it-200000); else if(it<=500000) tax=(0.2*(it-300000))+(0.1*100000); else if(it<=1000000) tax=(0.3*(it-500000))+(0.2*200000)+(0.1*100000); else tax=(0.4*(it-1000000))+(0.3*500000)+(0.2*200000)+(0.1*100000); System.out.println("Employee id: "+eid); System.out.println("Employee gender : "+gender); System.out.println("Income tax amount is "+tax); } } }
2 . An electronics shop has announced the following seasonal discounts on the purchase of certain items:Purchase Amount in Rs. Discount on Laptop Discount on Desktop 0-25000 0.0% 5.0% 25001-57000 5.0% 7.5% 57001-100000 7.5% 10.0% more than 100000 10.0% 15.0%
Write a program based on the above criteria to input name, address, amount of purchase and type of purchase(L for Laptop and D for Desktop) by the customer. compute and print the net amount to be paid by a customer along with his/ her name and address.
import java.util.*; public class laptop { public static void main(String args[]) { Scanner in = new Scanner(System.in); System.out.print("Enter name, address, amount and type [D or L]: "); String name=in.next(); String address=in.next(); double amt=in.nextDouble(); char type=in.next().charAt(0); char ch = Character.toUpperCase(type); double dis,net; switch(ch) { case 'L': if(amt<=25000) dis=0.0; else if(amt<=57000) dis=amt*5.0/100.0; else if(amt<=100000) dis=amt*7.5/100.0; else dis=amt*10.0/100.0; net=amt-dis; System.out.println("Name : "+name); System.out.println("Address : "+address); System.out.println("Purchase amount : "+amt); System.out.println("Discount : "+dis); System.out.println("Net amount : "+net); break; case 'D': if(amt<=25000) dis=amt*5.0/100.0; else if(amt<=57000) dis=amt*7.5/100.0; else if(amt<=100000) dis=amt*10/100.0; else dis=amt*15.0/100.0; net=amt-dis; System.out.println("Name : "+name); System.out.println("Address : "+address); System.out.println("Purchase amount : "+amt); System.out.println("Discount : "+dis); System.out.println("Net amount : "+net); break; default: System.out.println("Wrong input!"); dis=0.0;
}
}
}
3 . Write a menu driven program to accept a number from the user and check whether it a BUZZ’ number or to accept any two numbers and print their ‘GCD’.
Note:
- A BUZZ number is the number which either ends with digit 7 or is divisible by 7.
- GCD (Greatest Common Divisor) of two integers is calculated by continued division method Divide the larger number by the smaller, the remainder then divides the previous divisor. The process is repeated till the remainder is zero. The divisor then results in GCD.
import java.io.*;
public class Check
{
public static void main(String args[])throws IOException
{
int ch;
InputStreamReader read =new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
System.out.println("1. To check a BUZZ Number");
System.out.println("2. To find GCD of two numbers");
System.out.println("Enter your choice");
ch=Integer.parseInt(in.readLine());
switch(ch)
{
case 1:
int n;
System.out.println("Enter a number");
n=Integer.parseInt(in.readLine());
if(n%7==0||n%10==7)
System.out.println(n+"is a Buzz number");
else
System.out.println(n+"is not a Buzz number");
break;
case 2:
int a,b,t=0;
System.out.println("Enter first number");
a=Integer.parseInt(in.readLine());
System.out.println("Enter second number");
b=Integer.parseInt(in.readLine());
while(a%b!=0)
{
t=a%b;
a=b;
b=t;
}
System.out.println("GCD of two numbers ="+b);
break;
default:
System.out.println("Wrong choice!!");
}
}
}