Using Switch Case for Intervals

5
My teacher passed an exercise in which we should use the cases of a switch to handle intervals, he said strictly that we should use the switch and we can not use if nor while/do . I've tried the following code:

switch(saldo){

        case 0..200:
            //...
        break;
}

However, I know that java does not work this way, I already searched the internet for a .. and I did not find anything that solved my problem, how can I do that?

Statement:

  

4) A bank will grant special credit to its customers, variable   with the average balance in the last year. Make an algorithm that reads the balance   average of a customer and calculate the value of the credit according to the   table below. Display a message stating the average balance and   of credit. (use the case-of command and do no reps)

     

Average Percentage Balance

     

0 to 200 no credit

     

201 to 400 20% of the average balance amount

     

from 401 to 600 30% of the average balance amount

     

above 601 40% of the average balance amount

    
asked by anonymous 24.11.2017 / 18:17

1 answer

10

Pure mathematics:

class Ideone {
    public static void main (String[] args) {
        int x = 534;
        switch (x / 200) {
            case 0:
                System.out.println("entre 0 e 199");
                break;
            case 1:
                System.out.println("entre 200 e 399");
                break;
            case 2:
                System.out.println("entre 400 e 599");
                break;
            default:
                System.out.println("600 ou mais");
                break;
        }
    }
}

See working on ideone . And no Coding Ground . Also I put it in GitHub for future reference .

The original version did not have the statement, but what changes is detail, the secret is to divide by the size of the range.

Actually the statement is impossible, or at least very complex and would have to use another auxiliary mechanism such that the switch will be noise, because not all intervals are equal, but must be error of the statement, to say "above 601" what would make 601 in limbo. You can do this as long as you create an auxiliary array with the possible ranges, or in this case simpler handle the exception of the first case (only it seems to be different).

Something like this:

((x == 0 ? 1 : x) - 1) / 200

Obviously I would need to change the texts I used.

Unless the teacher wants you to do this:

switch (x) {
case 0:
case 1:
case 2:
    .
    .
    .
case 200:
    System.out.println("entre 0 e 199");
    break;
case 201:
case 202:
case 203:
    .
    .
    .
case 400:
    System.out.println("entre 200 e 400");
    break;
    .
    .
    .
    
24.11.2017 / 18:23