I am trying to make a function that I can refer to in my main method. With a double variable input X and string input Y, I want the function to do the following:
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:
def FunctionName(X,Y) {
//tasks
}
How do I do this in Java? And how would I call on it? Thanks!
First you will need to convert double
to String
. And If you want to return that String
then:
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
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.
ps: I converted double
to String
because why take that extra step of converting it to BigDecimal
first and then convert it to 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.
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.