Friday, 6 October 2023

JAVA

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 :

 
        
  1. /* Now we will see the same example which we
  2. taken in the if else statements blog
  3. but here we test is done for only 10 marks
  4. if marks are 10 - very good
  5. 9 - good
  6. 8 - nice
  7. 7 - better luck next time
  8. 6 - poor study hard
  9. 0 to 5 - stay here one more year
  10. */
  11. import java.util.* ;
  12. public class MINtech{
  13. public static void main(String args[]){
  14. // calling the scanner class
  15. Scanner sc = new Scanner(System.in);
  16. System.out.println("Enter your Maerks(0-10) : ") ;
  17. // taking int as a input
  18. int marks = sc.nextInt();
  19. // Initializing switch condition
  20. switch(marks){
  21. // checking whether the num is equals to 0 or 1 or 2 or
  22. //3 or 4 or 5 or not
  23. case 0 :
  24. case 1 :
  25. case 2 :
  26. case 3 :
  27. case 4:
  28. case 5 :
  29. System.out.println("Fail : stay here one more year ");
  30. break ;
  31. case 6 :
  32. System.out.println("Poor - Study hard");
  33. break;
  34. case 7 :
  35. System.out.println("Better luck next time ");
  36. break ;
  37. case 8 :
  38. System.out.println("Nice");
  39. break;
  40. case 9 :
  41. System.out.println("Good");
  42. break ;
  43. case 10 :
  44. System.out.println("Very Good");
  45. break;
  46. // default will executed if num is not matched with
  47. // the anyone of the above mentioned cases
  48. default:
  49. System.out.println("Inavalid marks");
  50. break ;
  51. }
  52. }
  53. }

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

        
https://www.highcpmrevenuegate.com/s4ttwmua2u?key=c02c9252219c2ddb8d72b452016a4796

No comments:

Post a Comment