简体   繁体   中英

On Switch How to use logic operator on case JAVA

i have a problem i dont know what to put on case section, when ever the user input their grades from 0-100 there are output corresponds to their grades failed,good,verygood,excellent.

import java.util.Scanner;
public class ProgTestI {


    public static void main (String args[]){

        Scanner pao = new Scanner(System.in);
        System.out.print("Grades: ");
        String grades = pao.next();
        int grado = Integer.parseInt(grades);

        switch (grado){

        case =<74: /* iwant to put 0 to 74*/

            System.out.println("Failed");



        case : /* 75-80*/

            System.out.println("bellow average");


        case : /*81-85*/

            System.out.println("average");

        case : /*86-90*/

            System.out.println("Good");

        case : /*91-96*/

            System.out.println("VeryGood");

        default:







        }




    }

}

You cannot use switch for ranges, you need to replace this chunk of code with proper if/else blocks. Switch works only on numeric values, but it works like

if(numericVal == 40)

So writing it for ranges is... waste of code, and not readable.

You need to rewrite it:

if( g <= 74){
 ...
}else if( g > 74 && g <= 80 ){ 
...

Your case code is incorrect, you can do as Beri mentioned.

If you want to implement switch statement in your application, then you can do as follows:

public static void main(String[] args) {
    Scanner pao = new Scanner(System.in);
    System.out.print("Grades: ");
    String grades = pao.next();
    int grado = Integer.parseInt(grades);
    int checkedCase=0;
    if(grado<=74){
        checkedCase=1;
    }
    else if(grado>=75&&grado<=80){
        checkedCase=2;
    }
    else if(grado>=81&&grado<=85){
        checkedCase=3;
    }
    else if(grado>=86&&grado<=90){
        checkedCase=4;
    }
    else if(grado>=91&&grado<=96){
        checkedCase=5;
    }

    switch (checkedCase){

    case 1: /* iwant to put 0 to 74*/

        System.out.println("Failed");
        break;


    case 2: /* 75-80*/

        System.out.println("bellow average");
        break;

    case 3: /*81-85*/

        System.out.println("average");
        break;
    case 4: /*86-90*/

        System.out.println("Good");
        break;
    case 5: /*91-96*/

        System.out.println("VeryGood");
           break;

    default: System.out.println("Please enter a value in range 0-96");
        break;
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM