如何在Java中创建一个单一的代码函数,以便多次运行它?

huangapple go评论67阅读模式
英文:

How to create a single code function in Java to run it multiple time?

问题

以下是我写的代码。我将在多个Java文件中使用相同的函数(process),或者在同一个Java文件中多次使用相同的函数(process)。现在我想知道如何创建一个单独的函数,以便在任何地方都可以运行它,而不必一遍又一遍地编写相同的代码。

以下是我的代码:

String roglines = new BigDecimal(String.valueOf(rog)).toString();
String zidlines = roglines.substring(0, roglines.indexOf('.'));
String zidlineslast = roglines.substring(roglines.indexOf('.'), roglines.length());

BigDecimal getposlines = new BigDecimal(zidlineslast);
poslines = getposlines.multiply(new BigDecimal("9.478"));
if (poslines.scale() == 0) {
    poslines = poslines.setScale(2, RoundingMode.CEILING);
}
String wollines = new BigDecimal(String.valueOf(poslines)).toString();
String toplines = wollines.substring(0, wollines.indexOf('.'));
String toplineslast = wollines.substring(wollines.indexOf('.'), wollines.length());
BigDecimal endlines = new BigDecimal(toplineslast);
finallines = endlines.multiply(new BigDecimal("145"));
英文:

Below is code that I have written. I will use the same function (process) in multiple Java files or in the same Java file multiple times. Now I want to know how do I create a single code function to run it everywhere without writing the same code again and again.

Here is my code:

String roglines= new BigDecimal(String.valueOf(rog)).toString();
String zidlines= roglines.substring( 0,roglines.indexOf('.'));
String zidlineslast = roglines.substring( roglines.indexOf('.'), roglines.length());

BigDecimal getposlines= new BigDecimal(zidlineslast );
poslines= getposlines.multiply(new BigDecimal("9.478"));
if (poslines.scale() == 0) {
    poslines= poslines.setScale(2, RoundingMode.CEILING);
}
String wollines= new BigDecimal(String.valueOf(poslines)).toString();
String toplines= wollines.substring( 0,wollines.indexOf('.'));
String toplineslast = wollines.substring( wollines.indexOf('.'), wollines.length());
BigDecimal endlines= new BigDecimal(toplineslast );
finallines = endlines.multiply(new BigDecimal("145"));

答案1

得分: 1

首先,弄清楚代码中使用的参数。例如,你已经硬编码了 new BigDecimal("9.478"),可以将 9.478 作为参数传递。然后,简单地创建一个方法并传递这些参数。

英文:

First figure out the parameters that is being used by your code. For example you have hard coded new BigDecimal("9.478") 9.478 can be passed as parameter. Then simply create a method and pass those parameters.

答案2

得分: 1

// 定义一个类,将你的代码放入一个方法中

您希望从不同的地方调用此方法因此我们肯定不希望将此代码复制粘贴到各个地方让我们创建一个带有执行计算的方法的类

```java
package work.basil.demo;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class RogZidPosWolTop
{
    // 为您的魔法数字命名。我不知道它们的含义,所以我将x和y因子作为名称。您可以取更好的名字。
    static final private BigDecimal XFACTOR = new BigDecimal("9.478");
    static final private BigDecimal YFACTOR = new BigDecimal("145");

    public BigDecimal calculateTopFromRog(final BigDecimal rog)
    {
        // `divideAndRemainder` 返回一个包含两个元素的 BigDecimal 数组,其中包含两个操作数上 divideToIntegralValue 和 remainder 的结果。
        BigDecimal[] zids = rog.divideAndRemainder(BigDecimal.ONE);
        BigDecimal zid = zids[0];  // rog 的整数部分。
        BigDecimal zidLast = zids[1];  // rog 的小数部分。

        BigDecimal pos = zidLast.multiply(RogZidPosWolTop.XFACTOR);
        if (pos.scale() == 0)
        {
            pos = pos.setScale(2, RoundingMode.CEILING); // 当尺度为零时为什么设置尺度?我不理解您在这里的逻辑。
        }

        BigDecimal[] tops = pos.divideAndRemainder(BigDecimal.ONE);
        BigDecimal top = tops[0];  // pos 的整数部分。
        BigDecimal topLast = tops[1];  // pos 的小数部分。

        BigDecimal result = topLast.multiply(RogZidPosWolTop.YFACTOR);
        return result;
    }

}

示例用法:

RogZidPosWolTop rogZidPosWolTop = new RogZidPosWolTop();
BigDecimal x = rogZidPosWolTop.calculateTopFromRog(new BigDecimal("42.7"));
System.out.println("x = " + x);

>x = 101.5

如果您不了解面向对象编程的基础知识,如类、方法和实例,您需要进行更多的学习。您可以免费在线阅读 Oracle 的 Java 教程 作为入门指南。同时阅读许多优秀的书籍,比如 Head First Java(可能已过时,但仍然适合基础知识)。


使用智能对象而不是简单字符串

我重新编写了您的代码。您的思路是基于字符串操作,但处理数字的方式并不明智。

与其使用简单的字符串,不如使用智能对象。BigDecimal 是智能的,它知道如何进行数学计算。它提供了获取整数部分和小数部分的方法。因此,学会使用这些方法会更好。请注意,在这个重新编写的代码中,我完全没有使用String 或文本。

您似乎在将字符串分割为获取整数和小数部分时使用了一种笨拙的方法。相反,我调用了 BigDecimal::divideAndRemainder 来除以 1。这将返回一个由两个元素组成的数组。第一个元素是整数值的 BigDecimal。第二个元素是等同于从原始数字中减去整数部分后的小数部分。参见这个问题,How to get integer and fraction portions of a BigDecimal in Java

BigDecimal[] zids = new BigDecimal("42.7").divideAndRemainder(BigDecimal.ONE);
System.out.println(Arrays.toString(zids));

>[42.0, 0.7]

需要注意的是,如果输入是负数,则在使用 divideAndRemainder 时,整数部分和小数部分都将是负数;我无法确定这是否适用于您的问题。如果不适用,请对小数部分取绝对值

您没有解释您的逻辑或细节。您没有给出示例输入和输出。您也没有将您的命名翻译成英文。因此,我只能猜测是否正确。但至少,这应该能帮助您更好地解决问题。

// 为您的魔法数字命名。我不知道它们的含义,所以我将x和y因子作为名称。您可以取更好的名字。
BigDecimal xFactor = new BigDecimal("9.478");
BigDecimal yFactor = new BigDecimal("145");

// 输入
BigDecimal rog = new BigDecimal("42.7"); // 示例数据。根据问题中未说明的rog变量的类型进行猜测。

// `divideAndRemainder` 返回一个包含两个元素的 BigDecimal 数组,其中包含两个操作数上 divideToIntegralValue 和 remainder 的结果。
BigDecimal[] zids = rog.divideAndRemainder(BigDecimal.ONE);
BigDecimal zid = zids[0];  // rog 的整数部分。
BigDecimal zidLast = zids[1];  // rog 的小数部分。

BigDecimal pos = zidLast.multiply(xFactor);
if (pos.scale() == 0)
{
    pos = pos.setScale(2, RoundingMode.CEILING); // 当尺度为零时为什么设置尺度?我不理解您在这里的逻辑。
}

BigDecimal[] tops = pos.divideAndRemainder(BigDecimal.ONE);
BigDecimal top = tops[0];  // pos 的整数部分。
BigDecimal topLast = tops[1];  // pos 的小数部分。

BigDecimal result = topLast.multiply(yFactor);
英文:

Define a class, put your code into a method there

You want to call this from various places. So we certainly do not want to be copy-pasting this code into various places. Let's create a class with a method to do the calculations.

package work.basil.demo;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class RogZidPosWolTop
{
    // Name your magic numbers. I do not know their meaning, so I invented x and y factor as the names. You can do better.
    static final private BigDecimal XFACTOR = new BigDecimal( "9.478" );
    static final private BigDecimal YFACTOR = new BigDecimal( "145" );

    public BigDecimal calculateTopFromRog ( final BigDecimal rog )
    {
        // `divideAndRemainder` returns a two-element BigDecimal array containing the result of divideToIntegralValue followed by the result of remainder on the two operands.
        BigDecimal[] zids = rog.divideAndRemainder( BigDecimal.ONE );
        BigDecimal zid = zids[ 0 ];  // integer portion of rog.
        BigDecimal zidLast = zids[ 1 ];  // fractional portion of rog.

        BigDecimal pos = zidLast.multiply( RogZidPosWolTop.XFACTOR );
        if ( pos.scale() == 0 )
        {
            pos = pos.setScale( 2 , RoundingMode.CEILING ); // Why set the scale when it is zero? I do not understand your logic here.
        }

        BigDecimal[] tops = pos.divideAndRemainder( BigDecimal.ONE );
        BigDecimal top = zids[ 0 ];  // integer portion of pos.
        BigDecimal topLast = zids[ 1 ];  // fractional portion of pos.

        BigDecimal result = topLast.multiply( RogZidPosWolTop.YFACTOR );
        return result;
    }

}

Example usage:

        RogZidPosWolTop rogZidPosWolTop = new RogZidPosWolTop();
        BigDecimal x = rogZidPosWolTop.calculateTopFromRog( new BigDecimal( "42.7" ) );
        System.out.println( "x = " + x );

>x = 101.5

If you do not understand the basics of object-oriented programming such as classes, methods, and instances, you need more study. Read the Java Tutorials by Oracle as a starter, free-of-cost online. And read any number of good books such as Head First Java (outdated but may still be good for the basics).


Smart objects rather than dumb strings

I rewrote your code. You are thinking in terms of string manipulation. This is not a wise way to handle numbers.

Better to use smart objects rather than dumb strings. A BigDecimal is smart, it knows how to do math. It offers methods to get the integer port and the fractional part. So learn to use those methods. Notice that I make no use of String or text at all in this rewritten code.

You seem to be chopping strings as an awkward way to get the integer and fractional portions of the number. Instead, I call BigDecimal::divideAndRemainder to divide by one. This returns an array of two elements. The first is a BigDecimal with the integer value. The second is the fractional amount, equivalent to if we had subtract the integer value from our original number. See this Question, How to get integer and fraction portions of a BigDecimal in Java.

BigDecimal[] zids = new BigDecimal( "42.7" ).divideAndRemainder( BigDecimal.ONE );
System.out.println( Arrays.toString( zids ) );

>[42.0, 0.7]

Notice that if the input is a negative number, both the integer and the fraction will be negative as well when using divideAndRemainder; I cannot know if this is appropriate to your problem or not. If not, take the absolute value of the fractional portion.

You have not explained your logic or details. You gave no example inputs-outputs. And you did not translate your naming to English. So I can only guess if I got this right. But it should, at least, get you going in a better direction.

// Name your magic numbers. I do not know their meaning, so I invented x and y factor. You can do better.
BigDecimal xFactor = new BigDecimal( "9.478" );
BigDecimal yFactor = new BigDecimal( "145" );

// Input
BigDecimal rog = new BigDecimal( "42.7" ); // Example data. Guessing as to the type of your `rog` variable, not stated in the Question.

// `divideAndRemainder` returns a two-element BigDecimal array containing the result of divideToIntegralValue followed by the result of remainder on the two operands.
BigDecimal[] zids = rog.divideAndRemainder( BigDecimal.ONE );
BigDecimal zid = zids[ 0 ];  // integer portion of rog.
BigDecimal zidLast = zids[ 1 ];  // fractional portion of rog.

BigDecimal pos = zidLast.multiply( xFactor );
if ( pos.scale() == 0 )
{
    pos = pos.setScale( 2 , RoundingMode.CEILING ); // Why set the scale when it is zero? I do not understand your logic here.
}

BigDecimal[] tops = pos.divideAndRemainder( BigDecimal.ONE );
BigDecimal top = zids[ 0 ];  // integer portion of pos.
BigDecimal topLast = zids[ 1 ];  // fractional portion of pos.

BigDecimal result = topLast.multiply( yFactor );

答案3

得分: 0

我不知道rog是什么类型的对象,因此将其表示为泛型 T。您可以将其替换为准确的对象类型。

public BigDecimal method(T rog, BigDecimal c1, BigDecimal c2){
    String rogLines = String.valueOf(rog);
    String zidLines = rogLines.substring(0, rogLines.indexOf('.'));
    String zidLinesLast = rogLines.substring(rogLines.indexOf('.'), rogLines.length());

    BigDecimal getPosLines = new BigDecimal(zidLinesLast);
    posLines = getPoslines.multiply(c1);
    if (posLines.scale() == 0) {
        posLines = posLines.setScale(2, RoundingMode.CEILING);
    }
    String wollines = String.valueOf(posLines);
    String topLines = wollines.substring(0, wollines.indexOf('.'));
    String topLinesLast = wollines.substring(wollines.indexOf('.'), wollines.length());
    BigDecimal endLines = new BigDecimal(topLinesLast);
    BigDecimal finalLines = endLines.multiply(c2);
    return finalLines;
}

我假设您进行所有这些操作是为了获取 finalLines 的值,因此我返回了它。

PS: Java 遵循驼峰命名法来命名变量。

英文:

I don't know what type of object rog is, hence putting it generic as T. You can replace it with the exact object type.

public BigDecimal method(T rog, BigDecimal c1, BigDecimal c2){
    String rogLines= String.valueOf(rog);
    String zidLines= rogLines.substring( 0,rogLines.indexOf('.'));
    String zidLinesLast = rogLines.substring( rogLines.indexOf('.'), rogLines.length());
    
    BigDecimal getPosLines= new BigDecimal(zidLinesLast);
    posLines= getPoslines.multiply(c1);
    if (posLines.scale() == 0) {
        posLines= posLines.setScale(2, RoundingMode.CEILING);
    }
    String wollines= String.valueOf(posLines);
    String topLines= wollines.substring( 0,wollines.indexOf('.'));
    String topLinesLast = wollines.substring( wollines.indexOf('.'), wollines.length());
    BigDecimal endLines= new BigDecimal(topLinesLast);
    BigDecimal finalLines = endLines.multiply(c2);
    return finalLines;
}

I have assumed that you are doing all this to get the value of finallines and hence I am returning that.

PS : Java follows camelCase way of naming variables.

答案4

得分: 0

假设你的代码在类 A 的方法 someFunc() 中。

注意:(a) 使你的函数成为静态函数,这样每次调用该方法时都不需要创建类对象。

(b) 同样地,我将返回类型设为 void,因为你的代码中没有指定任何返回类型。

情况一:从同一个 Java 类/文件中调用该函数:

class A
{
  public static void someFunc()
  {  
     String roglines = new BigDecimal(String.valueOf(rog)).toString();
     String zidlines = roglines.substring(0, roglines.indexOf('.'));
     String zidlineslast = roglines.substring(roglines.indexOf('.'), roglines.length());

     BigDecimal getposlines = new BigDecimal(zidlineslast);
     poslines = getposlines.multiply(new BigDecimal("9.478"));
     if (poslines.scale() == 0) {
       poslines = poslines.setScale(2, RoundingMode.CEILING);
     }
     String wollines = new BigDecimal(String.valueOf(poslines)).toString();
     String toplines = wollines.substring(0, wollines.indexOf('.'));
     String toplineslast = wollines.substring(wollines.indexOf('.'), wollines.length());
     BigDecimal endlines = new BigDecimal(toplineslast);
     finallines = endlines.multiply(new BigDecimal("145"));
     return finallines;
  }
  public void callingYourFunc()
  {
    BigDecimal yourValue = someFunc(); //your method has been called and your code has been processed
  }
}

情况二:从其他类/文件中导入你的代码,使用完整的包引用:

import com.your.package.classA;

class B
{
   public void callingFunc()
   {
     BigDecimal yourValue = classA.someFunc();
     System.out.println("Value after calling my code=" + yourValue);
   }
}
英文:

Lets's suppose your code is in method someFunc() in class A.

Note: (a) Make your function static so that you need create class object everytime you need to invoke the method.

(b) Also, I am returning void as you have not mentioned any return type in your code.

Case I: Invoking the function from same java class/file:

class A
{
  public static void someFunc()
  {  
     String roglines= new BigDecimal(String.valueOf(rog)).toString();
     String zidlines= roglines.substring( 0,roglines.indexOf('.'));
     String zidlineslast = roglines.substring( roglines.indexOf('.'), 
     roglines.length());

     BigDecimal getposlines= new BigDecimal(zidlineslast );
     poslines= getposlines.multiply(new BigDecimal("9.478"));
     if (poslines.scale() == 0) {
       poslines= poslines.setScale(2, RoundingMode.CEILING);
     }
     String wollines= new BigDecimal(String.valueOf(poslines)).toString();
     String toplines= wollines.substring( 0,wollines.indexOf('.'));
     String toplineslast = wollines.substring( wollines.indexOf('.'), 
     wollines.length());
     BigDecimal endlines= new BigDecimal(toplineslast );
     finallines = endlines.multiply(new BigDecimal("145"));
     return finallines;
  }
  public void callingYourFunc()
  {
    BigDecimal yourValue= someFunc(); //your method has been called and your code has been processed
  }
}

Case 2: Invoking your code from other class/file.Import your class with complete package reference:

classA
{
  public static void someFunc()
  {  
          String roglines= new BigDecimal(String.valueOf(rog)).toString();
     String zidlines= roglines.substring( 0,roglines.indexOf('.'));
     String zidlineslast = roglines.substring( roglines.indexOf('.'), 
     roglines.length());

     BigDecimal getposlines= new BigDecimal(zidlineslast );
     poslines= getposlines.multiply(new BigDecimal("9.478"));
     if (poslines.scale() == 0) {
       poslines= poslines.setScale(2, RoundingMode.CEILING);
     }
     String wollines= new BigDecimal(String.valueOf(poslines)).toString();
     String toplines= wollines.substring( 0,wollines.indexOf('.'));
     String toplineslast = wollines.substring( wollines.indexOf('.'), 
     wollines.length());
     BigDecimal endlines= new BigDecimal(toplineslast );
     finallines = endlines.multiply(new BigDecimal("145"));
     return finallines;
  }
}

import com.your.package.classA;
class B
{
   public void callingFunc()
   {
     BigDecimal yourValue = classA.someFunc();
     System.out.println("Value after calling my code="+yourValue);
   }
}

</details>



# 答案5
**得分**: 0

你的问题不够清楚。但据我理解,你想编写一段代码(方法)并在各处重复使用。

你有两个选择:

1- 你可以在一个类内部实现该方法,比如说 `ClassA`。然后在另一个类内部(比如说 `ClassB`)实例化 `ClassA`,像这样:`ClassA classA = new ClassA()`。然后可以通过 `classA.yourMethod()` 调用你的方法。

2- 如果你期望的功能更像是一个实用方法,你可以将其定义为 `static` 方法,这样就不需要实例化它所在的类,比如:

```java
public class ClassB {

    public static void main(String[] args){
        ClassA.yourMethod();
    }
}
英文:

Your question is not clear enough. But as far as I understood you want to write a peace of code (method) and use it everywhere.

you have 2 options

1- you can implement the method inside a class say ClassA. then instantiate the ClassA inside -say- ClassB like ClassA classA = new ClassA(). Then call your method like classA.yourMethod()

2- If your desired functionality is more like utility method, you can define it as static method and call it everywhere without having to instantiate its class like :

public ClassB {

public static void main(String[] args){
ClassA.yourMethod();
}
}

</details>



huangapple
  • 本文由 发表于 2020年7月25日 12:03:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/63084184.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定