varias valores valor sentencia retornar retornan retorna que para objeto metodos metodo java function return-value

java - valores - retornar un valor en c#



¿Cómo devolver 2 valores desde un método Java? (13)

Estoy intentando devolver 2 valores de un método de Java pero obtengo estos errores. Aquí está mi código:

// Method code public static int something(){ int number1 = 1; int number2 = 2; return number1, number2; } // Main method code public static void main(String[] args) { something(); System.out.println(number1 + number2); }

Error:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - missing return statement at assignment.Main.something(Main.java:86) at assignment.Main.main(Main.java:53)

Resultado de Java: 1


Devuelve una matriz de objetos

private static Object[] f () { double x =1.0; int y= 2 ; return new Object[]{Double.valueOf(x),Integer.valueOf(y)}; }


En lugar de devolver una matriz que contenga los dos valores o utilizar una clase Pair genérica, considere crear una clase que represente el resultado que desea devolver, y devolver una instancia de esa clase. Dale a la clase un nombre significativo. Los beneficios de este enfoque sobre el uso de una matriz son de seguridad tipo y hará que su programa sea mucho más fácil de entender.

Nota: Una clase de Pair genérica, como se propone en algunas de las otras respuestas aquí, también le da seguridad de tipo, pero no transmite lo que representa el resultado.

Ejemplo (que no usa nombres realmente significativos):

final class MyResult { private final int first; private final int second; public MyResult(int first, int second) { this.first = first; this.second = second; } public int getFirst() { return first; } public int getSecond() { return second; } } // ... public static MyResult something() { int number1 = 1; int number2 = 2; return new MyResult(number1, number2); } public static void main(String[] args) { MyResult result = something(); System.out.println(result.getFirst() + result.getSecond()); }


En mi opinión, lo mejor es crear una nueva clase cuyo constructor es la función que necesita, por ejemplo:

public class pairReturn{ //name your parameters: public int sth1; public double sth2; public pairReturn(int param){ //place the code of your function, e.g.: sth1=param*5; sth2=param*10; } }

Entonces simplemente use el constructor como usaría la función:

pairReturn pR = new pairReturn(15);

y puede usar pR.sth1, pR.sth2 como "2 resultados de la función"


Java no admite devoluciones de múltiples valores. Devuelve una matriz de valores.

// Function code public static int[] something(){ int number1 = 1; int number2 = 2; return new int[] {number1, number2}; } // Main class code public static void main(String[] args) { int result[] = something(); System.out.println(result[0] + result[1]); }


No necesita crear su propia clase para devolver dos valores diferentes. Solo use un HashMap como este:

private HashMap<Toy, GameLevel> getToyAndLevelOfSpatial(Spatial spatial) { Toy toyWithSpatial = firstValue; GameLevel levelToyFound = secondValue; HashMap<Toy,GameLevel> hm=new HashMap<>(); hm.put(toyWithSpatial, levelToyFound); return hm; } private void findStuff() { HashMap<Toy, GameLevel> hm = getToyAndLevelOfSpatial(spatial); Toy firstValue = hm.keySet().iterator().next(); GameLevel secondValue = hm.get(firstValue); }

Incluso tiene el beneficio de tipo de seguridad.


Podría implementar un Pair genérico si está seguro de que solo necesita devolver dos valores:

public class Pair<U, V> { /** * The first element of this <code>Pair</code> */ private U first; /** * The second element of this <code>Pair</code> */ private V second; /** * Constructs a new <code>Pair</code> with the given values. * * @param first the first element * @param second the second element */ public Pair(U first, V second) { this.first = first; this.second = second; } //getter for first and second

y luego haga que el método devuelva ese Pair :

public Pair<Object, Object> getSomePair();


Prueba esto :

// Function code public static int[] something(){ int number1 = 1; int number2 = 2; return new int[] {number1, number2}; } // Main class code public static void main(String[] args) { int[] ret = something(); System.out.println(ret[0] + ret[1]); }


Solo puede devolver un valor en Java, por lo que la mejor manera es la siguiente:

return new Pair<Integer>(number1, number2);

Aquí hay una versión actualizada de su código:

public class Scratch { // Function code public static Pair<Integer> something() { int number1 = 1; int number2 = 2; return new Pair<Integer>(number1, number2); } // Main class code public static void main(String[] args) { Pair<Integer> pair = something(); System.out.println(pair.first() + pair.second()); } } class Pair<T> { private final T m_first; private final T m_second; public Pair(T first, T second) { m_first = first; m_second = second; } public T first() { return m_first; } public T second() { return m_second; } }


También puede enviar objetos mutables como parámetros; si utiliza métodos para modificarlos, se modificarán cuando regrese de la función. No funcionará en cosas como Float, ya que es inmutable.

public class HelloWorld{ public static void main(String []args){ HelloWorld world = new HelloWorld(); world.run(); } private class Dog { private String name; public void setName(String s) { name = s; } public String getName() { return name;} public Dog(String name) { setName(name); } } public void run() { Dog newDog = new Dog("John"); nameThatDog(newDog); System.out.println(newDog.getName()); } public void nameThatDog(Dog dog) { dog.setName("Rutger"); } }

El resultado es: Rutger


Tengo curiosidad de por qué nadie ha encontrado la solución de devolución de llamada más elegante. Entonces, en lugar de utilizar un tipo de devolución, utiliza un controlador pasado al método como argumento. El siguiente ejemplo tiene los dos enfoques contrastantes. Sé cuál de los dos es más elegante para mí. :-)

public class DiceExample { public interface Pair<T1, T2> { T1 getLeft(); T2 getRight(); } private Pair<Integer, Integer> rollDiceWithReturnType() { double dice1 = (Math.random() * 6); double dice2 = (Math.random() * 6); return new Pair<Integer, Integer>() { @Override public Integer getLeft() { return (int) Math.ceil(dice1); } @Override public Integer getRight() { return (int) Math.ceil(dice2); } }; } @FunctionalInterface public interface ResultHandler { void handleDice(int ceil, int ceil2); } private void rollDiceWithResultHandler(ResultHandler resultHandler) { double dice1 = (Math.random() * 6); double dice2 = (Math.random() * 6); resultHandler.handleDice((int) Math.ceil(dice1), (int) Math.ceil(dice2)); } public static void main(String[] args) { DiceExample object = new DiceExample(); Pair<Integer, Integer> result = object.rollDiceWithReturnType(); System.out.println("Dice 1: " + result.getLeft()); System.out.println("Dice 2: " + result.getRight()); object.rollDiceWithResultHandler((dice1, dice2) -> { System.out.println("Dice 1: " + dice1); System.out.println("Dice 2: " + dice2); }); } }


Use un objeto tipo Pair / Tuple, ni siquiera necesita crear uno si depende de Apache commons-lang. Solo usa la clase Pair .


tienes que usar colecciones para devolver más de un valor de retorno

en su caso, escriba su código como

public static List something(){ List<Integer> list = new ArrayList<Integer>(); int number1 = 1; int number2 = 2; list.add(number1); list.add(number2); return list; } // Main class code public static void main(String[] args) { something(); List<Integer> numList = something(); }


public class Mulretun { public String name;; public String location; public String[] getExample() { String ar[] = new String[2]; ar[0]="siva"; ar[1]="dallas"; return ar; //returning two values at once } public static void main(String[] args) { Mulretun m=new Mulretun(); String ar[] =m.getExample(); int i; for(i=0;i<ar.length;i++) System.out.println("return values are: " + ar[i]); } } o/p: return values are: siva return values are: dallas