How to create a switch.. case with value ranges?

Asked

Viewed 2,197 times

-3

If a total of days is over 30 and under 60, I do something. If it’s over 60 and under 90 I do something else and so on. How do I do this case? Did the case is the best option?

  • 1

    explain one thing to me. What would be "and so on"? Do you want to stop at what point? Up to 120? 150, 270, 300? I didn’t get it.

  • 1

    Give examples of the behavior you want within each condition: from 30 to 60 what will be done; from 60 to 90 what will be done?

5 answers

2

Good afternoon,

Very interesting question, I just came across this problem in a course I’m doing.

I saw the solution of a colleague here in the forum in the Java language:

class Main {
    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;
        }
    }
}

I leave the link to those who are interested, it was a very clear explanation.

Using Switch Case for Ranges

The only change I had to make in the case of C# was to capture the entire division using the truncate method.

Math.Truncate Method

My code went like this:

         switch (Math.Truncate(average/2)){

          case 0: // 0 a 1                
            generalConcept = Concepts.E;
            break;

          case 1: // 2 a 3
            generalConcept = Concepts.D;                
            break;

          case 2: // 4 a 5
            generalConcept = Concepts.C;                
            break;

          case 3: // 6 a 7
            generalConcept = Concepts.B;                
            break;

          default: // 8 ou mais
            generalConcept = Concepts.A;                
            break;

        }

I hope I’ve helped!

2

Use if and else if thus:

int dias = 60;

if (dias < 30)
{
    System.Console.WriteLine("até 29");
}
else if (dias < 60)
{
    System.Console.WriteLine("de 30 até 59");
}
else if (dias < 90)
{
    System.Console.WriteLine("de 60 até 89");
}
else if (dias < 120)
{
    System.Console.WriteLine("de 90 até 119");
}
else
{
    System.Console.WriteLine("acima de 120");
}
  • 1

    If you use dias = 1 will fall in the second if. Have to test the intervals in all cases, start and end, as in my answer, or else put all ifs, inside one another if (dias > 30).

  • In fact it lacked the initial range.

2

There are several ways.

Switch

With switch That’s what comes to mind:

int mes = (int)System.Math.Floor((decimal)dias / 30);

switch(mes){
    case 0:
        break;
    case 1:
        // faz uma coisa
        break;
    case 2:
        // faz outra
        break;
    case 3:
    case 4:
        // faz outra..
        break;
    default:
        break;
}

Of course, it would have to be seen before whether the intervals are multiples of 30 and whether they are open or closed.

If

With If, the most obvious would be:

if (dias > 30){
    if (dias < 60){
        // faz uma coisa
    }
    else if (dias < 90){
        // faz uma outra coisa
    }
    [...]
}

or depending on whether it is a command:

var outputDeDias = EvalDias(dias);

private string EvalDias(int dias){
    if (dias < 30){
        return null;
    }
    if (dias < 60){
        return "uma coisa";
    }
    if (dias < 90){
        return "outra coisa";
    }
    [...]

    return null;
}   

1

Come on. If it’s "like this," we can write something like this.

  public void Tests(int diasInseridos)
    {
        int dias = diasInseridos;
        bool selected = false;//variavel que aciona um 'break' no momento em que entramos em alguma condição(if/else) válida
        int comparadorInicial = 30;//variavel comparadora de valor menor
        int comparadorFinal = 60;//variavel comparadora de valor maior

        while (selected == false)
        {
            if (dias == null || dias <= 0)
            {
                //Aqui retorna nenhum dia
                selected = true;//booleano para sair do laço
            }
            else if (dias > comparadorInicial && dias < comparadorFinal)
            {
                //Seu código retorna de acordo com os dias que seu programa detectou
                selected = true;//booleano para sair do laço
            }
            else
            {
                comparadorInicial = comparadorInicial + 30;
                comparadorFinal = comparadorFinal + 30;
            }

        }

    }

0

You must use several if's and not a switch. The switch serves to compare point values, not being able to compare intervals as you indicated in the question.

if (30 <= tempo && tempo < 60)
{
}
else if (60 <= tempo && tempo < 90)
{
}

There you go cuddling them if's us else'successively as far as you need.

  • It really has to be by if. So it goes quiet. I thought by case it would, but I saw that.

  • @Bacco: you are confused the comparisons. In my first, it is not x < 30, but yes 30 < x && x < 60. The first if checks from 30 to 60, and the second from 60 to 90.

  • @Bacco: What I could have done, is to put one if initial, which does nothing with the condition tempo < 30... Oh yes, the others if'They wouldn’t need two checks... just as I alerted the author of the reply you quoted... and who has already edited your reply.

  • @Bacco: I understand your concern. = D It is a matter of optimization, my solution is less optimal. It would be even worse if there were no else, but still it would work... like with ifone after the other without being inside the else.

  • 1

    @Bacco: no need to delete your comments... this is important, imagine a beginner seeing this answer. Comments are a way to show what is more correct or less correct as well.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.