write Java program to store a number between 1 to 5 in a variable and print it in word using switch case statement
Answers
Answer
3.0/5
2
Ishu060
Ambitious
3 answers
73 people helped
Answer:
(i am writing the program with blueJ friendly envirnoment)
//program starts
import java.util.*;
class DaysOfWeeks
{
public static void main();
{
Scanner sc=new Scanner(System.in);
int n;
System.out.println("Enter the number between 1-7");
n = sc.nextInt();
switch(n)
{
case 1: System.out.println("Day corresponding to 1 is Sunday");
break;
case 2: System.out.println(" Day corresponding to 2 is Monday");
break;
case 3: System.out.println(" Day corresponding to 3 is Tuesday");
break;
case 4: System.out.println(" Day corresponding to 4 is Wednesday");
break;
case 5: System.out.println(" Day corresponding to 5 is Thursday");
break;
case 6: System.out.println(" Day corresponding to 6 is Friday");
break;
case 7: System.out.println(" Day corresponding to 8 is Saturday");
break;
default: System.out.println("Invalid");
}
}
}
Explanation:
in the first line i have imported the Scanner class.
After the main i have created an object for Scanner Class.
Then I have initialized a variable and told the user to input the value between 1-7.
Then I have started the switch command which works on the input given by user.
If user gave input as 1 the case 1 will work
If user gave input as 2 then case 2 will work
Is user gave input as 3 then case 3 will work
and so on...
if user gave any other input other than 1,2,3,4,5,6,7 then the default case will work which is at the last.
Break command is necessary between every case because if not given the program will execute all commands below it.
For example if break is not given and user input value as 3 then case 3 will run and all the cases below it will also run.
So break is necessary
Hope it helps