How to call distinct methods under various Case Switch conditions?

2

I have this code, and would like to know how to call a method from 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

        }
    
asked by anonymous 15.10.2017 / 23:15

1 answer

4

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

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

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

Also note that if you do not fit into any of the above cases, you still have break .

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 you, default for error handling.

Recommended reading:

15.10.2017 / 23:47