问题
I have a method which calculates the square root of only negative numbers
(which is sqrt(x)=sqrt(-x) +"*i" , where x is a double and "*i" is a string)
the problem I have is that this method returns a double and a string which are two different variable types, so the question is how do I make this method return both?:
public static **(what goes here?)** myFunction(double x){
return(sqrt(x)+"*i");
}
this code is wrong but I do not know how to fix it, any tips?
回答1:
In Java you can't return multiple values from methods.
What you could do is to define a custom type which wraps your string and double values. Eg:
public class MyResult {
private double res1;
private String res2;
public MyResult(double res1, String res2) {
this.res1 = res1;
this.res2 = res2;
}
}
And use this in your method:
public static MyResult myFunction(double x){
return new MyResult(sqrt(x),"*i");
}
回答2:
@Amila's answer is correct.
Another (worse) approach is to have the method return a List<Object> instance and expect to have at the first position of the list the Double value, and at the second position the String one. However, this is not recommended. This is for demonstration purposes only.
List<Object> listWith2Types = getItems();
Double doubleVal = (Double) listWith2Types.get(0);
String strVal = (String) listWith2Types.get(1);
--Update after the dislikes--
I agree this is a bad practice for the particular case the author is describing. However, there are situations where this is the only solution along with checking what instance each object is using instanceof.
For example when you have a list of instances that extend from the same class, but are of different sub-class.
来源:https://stackoverflow.com/questions/52643124/is-there-a-way-to-return-a-double-and-a-string-from-a-single-method-in-java