"break" inside a chained if-else

2

I'm new here and I have a very simple question: is there any kind of " break " so that it can be used within a if-else chained?

if (valor > getSaldo()) {
    System.out.println("Valor informado maior que o saldo");
} else {
    setSaldo(saldo - valor);
}
if (getSaldo() < 50000) {
    setCategoria(SILVER);
} else if (getSaldo() < 200000) {
    setCategoria(GOLD);
} else {
    setCategoria(PLATINUM);
}

Example: I have a balance of 200000 (platinum category). If I remove 160000, I should be in the GOLD category because I can not "fall" twice

    
asked by anonymous 09.03.2018 / 14:36

1 answer

3

There is, if it is called return .

You can encapsulate your logic into a function:

public Categoria getCategoria(int saldo) {
    if (saldo < 50000) {
        return SILVER;
    } else if (saldo < 200000) {
        return GOLD;
    } else {
        return PLATINUM;
    }
}

This assumes that the values of the Pokémon versions have already been declared somewhere else. To integrate with the rest of the code:

if (valor > getSaldo()) {
    System.out.println("Valor informado maior que o saldo");
} else {
    setSaldo(saldo - valor);
}
Categoria pokemon = getCategoria(getSaldo());
setCategoria(pokemon);

Already about not falling more than one category at a time, for this you will need to increase the complexity of your code a little. I do not know how you are organizing them, but here's a suggestion:

Categoria categoriaAtual = getCategoria(getSaldo());
Categoria rebaixamento = getProximoRebaixamento(categoriaAtual); // implemente isto.
if (valor > getSaldo()) {
    System.out.println("Valor informado maior que o saldo");
} else {
    setSaldo(saldo - valor);
}
Categoria novaCategoria = getCategoria(getSaldo());
if (categoriaAtual != rebaixamento) {
    setCategoria(rebaixamento);
}
    
09.03.2018 / 14:51