2.switch statement with ranges in JAVA
Lets get started
If the value of a case label falls within a case range that has already been used in the switch statement, the compiler rejects the code with an error message.
syntax :
case 0...4; // error case 5 ... 9; // ok
Elaborate with a simple example :
- /* Now we will see the same example which we
- taken in the if else statements blog
- but here we test is done for only 10 marks
- if marks are 10 - very good
- 9 - good
- 8 - nice
- 7 - better luck next time
- 6 - poor study hard
- 0 to 5 - stay here one more year
- */
- import java.util.* ;
- public class MINtech{
- public static void main(String args[]){
- // calling the scanner class
- Scanner sc = new Scanner(System.in);
- System.out.println("Enter your Maerks(0-10) : ") ;
- // taking int as a input
- int marks = sc.nextInt();
- // Initializing switch condition
- switch(marks){
- // checking whether the num is equals to 0 or 1 or 2 or
- //3 or 4 or 5 or not
- case 0 :
- case 1 :
- case 2 :
- case 3 :
- case 4:
- case 5 :
- System.out.println("Fail : stay here one more year ");
- break ;
- case 6 :
- System.out.println("Poor - Study hard");
- break;
- case 7 :
- System.out.println("Better luck next time ");
- break ;
- case 8 :
- System.out.println("Nice");
- break;
- case 9 :
- System.out.println("Good");
- break ;
- case 10 :
- System.out.println("Very Good");
- break;
- // default will executed if num is not matched with
- // the anyone of the above mentioned cases
- default:
- System.out.println("Inavalid marks");
- break ;
- }
- }
- }
Output
Enter your Maerks(0-10) : 5 Fail : stay here one more year Enter your Maerks(0-10) : 10 Very Good Enter your Maerks(0-10) : 56 Inavalid marks
No comments:
Post a Comment