How to return 2 objects at the same time in a Java method?

Asked

Viewed 824 times

4

 public class Equacao2Grau {

        int a, b, c;

        public int CalculoDelta(){

            return (int) (Math.pow(b, 2) - 4*a*c);
        }

        public int FormulaQuadratica(){
            int x1 = (int) (-b + Math.sqrt(CalculoDelta()) / 2*a);

            int x2 = (int) (-b - Math.sqrt(CalculoDelta()) / 2*a);

            return x1, x2;
        }

        public String exibeResultado(){

            return "X1 = " + this.FormulaQuadratica() + "\nX2 = " + this.FormulaQuadratica();
        }
    }
  • 2

    pq does not return an array/list or even an object?

  • Face Concatenates the returns separated by ; and then removes by possibilities public int Formulaquadratica(){ int X1 = (int) (-b + Math.sqrt(Calculodelta()) / 2a); int x2 = (int) (-b - Math.sqrt(Calculodelta()) / 2a); String return = X1 + ";" + x2; return Return; } After a Split(';') and display the variable position[1]

  • 1

    @Renansilveira has no need of it. If so it is better to return a array.

  • 1

    A tuple, javafx.util.Pair, can resolve. You can create a type with properties x1 and x2 also.

1 answer

1


You can return some data structure that satisfies your problem:

public class Equacao2Grau {

  int a, b, c;

  public int CalculoDelta() {

    return (int) (Math.pow(b, 2) - 4 * a * c);
  }

  public Map<String, Integer> FormulaQuadratica() {
    Map<String, Integer> resultado = new HashMap<>();
    int x1 = (int) (-b + Math.sqrt(CalculoDelta()) / 2 * a);

    int x2 = (int) (-b - Math.sqrt(CalculoDelta()) / 2 * a);

    resultado.put("x1", x1);
    resultado.put("x2", x2);

    return resultado;
  }

  public String exibeResultado() {
    Map<String, Integer> resultado = this.FormulaQuadratica();

    return "X1 = " + resultado.get("x1") + "\nX2 = " + resultado.get("x2");
  }
}

The Map allows you to "name" the result from the keys.

  • I think what he wants is a Set: a set of unique and non-repeated values without a specific order.

Browser other questions tagged

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