有没有办法从java中的单个方法返回Double AND St​​ring? [英] Is there a way to return a Double AND a String from a single method in java?

查看:54
本文介绍了有没有办法从java中的单个方法返回Double AND St​​ring?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种只计算负数的平方根的方法

I have a method which calculates the square root of only negative numbers

(这是sqrt(x)=sqrt(-x) +"*i",其中x是double"*i"是字符串)

(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?

推荐答案

在Java中,您不能从方法中返回多个值.

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");
}

这篇关于有没有办法从java中的单个方法返回Double AND St​​ring?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆