How to call different methods in different Switch Case conditions?

Asked

Viewed 1,148 times

2

I have this code, and I’d like to know how to call a method from the switch...case.

public static void opcoes(){

        System.out.println("Selecione o Algoritmo de Substituicao Desejado");
        System.out.println("1 - FIFO");
        System.out.println("2 - LRU");
        System.out.println("3 - Segunda Chance");
        System.out.println("4 - Otimo");

        Scanner input = new Scanner(System.in);
        int num;

        switch(num){
            case 1: //// faz a chamada de método referente a FIFO

        }
  • 1

    case 1: fifoMethod(); break; case 2: lruMethod(); break; ... that would be it?

  • 1

    That same vlw! a

  • @user90625 I edited the title to better reflect what you really want to know. If you disagree, you can undo the editing or try to add even better text

1 answer

4


You call the code normally, as if it were in the body of a method:

case 1:
  fifoMethod();
  break;
case 2:
  lruMethod();
  break;
...

Note that the switch requires you to have a destination point of the variable being "switch-Ada". These destination points are indicated by the various cases. A priori, the behavior is to leak from one case to the next, so it is necessary to put the breaks to indicate that this is not the desired behaviour.

Also note that if you don’t fit into any of the previous cases, you still have the default.

switch (num) {
    case 1:
      fifoMethod();
      break;
    case 2:
      lruMethod();
      break;
    case 3: //...
      break;
    case 4: //...
      break;
    default:
      System.out.println(num + ", entrada inválida");
}

We can use, for your case, the default for error handling.


Recommended reading:

Browser other questions tagged

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