简体   繁体   English

在Java中创建多变量函数

[英]Making a multivariable function in Java

I am trying to make a function that I can refer to in my main method. 我正在尝试创建一个我可以在我的main方法中引用的函数。 With a double variable input X and string input Y, I want the function to do the following: 使用双变量输入X和字符串输入Y,我希望该函数执行以下操作:

 BigDecimal bdX = new BigDecimal(X);
 String strX = String.valueOf(bdX.doubleValue());
 strX = strX.replaceAll("E", " x 10^");

 System.out.println("\nOutput = " + strX + Y);

In python you could define a function like so: 在python中你可以像这样定义一个函数:

def FunctionName(X,Y) {
//tasks
}

How do I do this in Java? 我如何用Java做到这一点? And how would I call on it? 我该怎么称呼呢? Thanks! 谢谢!

First you will need to convert double to String . 首先,您需要将double转换为String And If you want to return that String then: 如果你想返回那个String那么:

public static String function(double x, String y) { 
    String strX = Double.toString(x); //String.valueOf(x) would have worked fine too
    strX = strX.replaceAll("E", " x 10^");
    return strX + y;
}

Or if you just want to print it out and donot want it to return that String , then 或者,如果您只是想将其打印出来并且不希望它返回该String ,那么

public static void function(double x, String y) { 
    String strX = Double.toString(x);
    strX = strX.replaceAll("E", " x 10^");
    System.out.println("\nOutput = " + strX + Y);
}

Then you will just call the above method in your main method. 然后你将在main方法中调用上面的方法。

ps: I converted double to String because why take that extra step of converting it to BigDecimal first and then convert it to String . ps:我将double转换为String因为为什么要先将其转换为BigDecimal ,然后将其转换为String

I don't know if I understood you right, but I try to anser you ^^ 我不知道我是否理解你,但我试着给你留言^^

If you want to call the method from the main method, you have to make your method static. 如果要从main方法调用方法,则必须使方法保持静态。

It would look like: 它看起来像:

public static void main(String args) {
    yourMethod(10.0, "Test"); // calls your method with example params
}

public static void yourMethod(double X, String Y) {
    // Your tasks
    BigDecimal bdX = new BigDecimal(X);
    String strX = String.valueOf(bdX.doubleValue());
    strX = strX.replaceAll("E", " x 10^");
    System.out.println("\nOutput = " + strX + Y);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM