How to create a getter in Java that has incoming numbers and uses switch to select the outgoing number?

This is my wrong example:

switch (randomOperatorLogicka) { case 1: float vysledekLogicka; vysledekLogicka = cislo1Logicka + cislo2Logicka; this.vysledek = vysledekLogicka; return vysledekLogicka; break; case 2: vysledekLogicka = cislo1Logicka - cislo2Logicka; this.vysledek = vysledekLogicka; return vysledekLogicka; break; case 3: vysledekLogicka = cislo1Logicka * cislo2Logicka; this.vysledek = vysledekLogicka; return vysledekLogicka; break; case 4: if (cislo1Logicka == 0) { do { cislo2Logicka = random.nextInt(11); } while (cislo2Logicka != 0); vysledekLogicka = cislo1Logicka / cislo2Logicka; this.vysledek = vysledekLogicka; return vysledekLogicka; break; } else { vysledekLogicka = cislo1Logicka / cislo2Logicka; this.vysledek = vysledekLogicka; return vysledekLogicka; break; } } float vysledekLogickap; return vysledekLogickap; } 
  • one
    In your code, the error is that you have a float vysledekLogicka; inside case. Take it out before the switch - Tr1nks
  • one
    and break after the return superfluous - Victor
  • @ Victor agree) - Tr1nks

1 answer 1

 public double calculate (int randomOperatorLogicka, int cislo1Logicka, int cislo2Logicka) { double vysledekLogicka = 0; switch (randomOperatorLogicka) { case 1: vysledekLogicka = cislo1Logicka+cislo2Logicka; break; case 2: vysledekLogicka = cislo1Logicka-cislo2Logicka; break; case 3: vysledekLogicka = cislo1Logicka*cislo2Logicka; break; case 4: if (cislo1Logicka == 0) cislo2Logicka = ThreadLocalRandom.current().nextInt(1, 12); vysledekLogicka = cislo1Logicka/cislo2Logicka; break; } //this.vysledek = vysledekLogicka; return vysledekLogicka; } 
  • You have a lot of duplicate code, which makes it unreadable. Write your method like this, with the required values ​​as arguments, and accept the result. As you can see the line this.vysledek = vysledekLogicka; commented out. The fact is that you can uncomment it and it will work, but is it worth writing code like this ... This is a question for independent study. - Dmitriy
  • You should not write an addition to the answer in the comment :) Click the "edit" button under the answer and add directly what you would like to add to solve the issue, and delete the comment - pavlofff