-1

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"));
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 2
    Where is 'everywhere'? Do you mean you want to run this code several times in the same Java program? – tgdavies Jul 25 '20 at 04:05
  • What does the line ``String wollines= new BigDecimal(String.valueOf(poslines)).toString();`` do? It looks to me like it merely should be ``String wollines = String.valueOf(poslines);`` – NomadMaker Jul 25 '20 at 04:08
  • 2
    In java we use the term _method_ rather than _function_. You seem to want a public method. Do you know and understand the concept of classes in java? Do you know and understand what access modifiers are in java, i.e. `public`, `protected` and `private`? – Abra Jul 25 '20 at 04:27
  • 1
    What are roglines, zidlines, poslines, and such? If you explained your problem, there may be a better solution. You are thinking in terms of manipulating strings that represents numbers, and I suspect there must be a better approach than that. – Basil Bourque Jul 25 '20 at 04:38
  • What type is `rog` in your first line? – Basil Bourque Jul 25 '20 at 04:41
  • Ways to improve this Question: Explain your logic or details. Give example inputs-outputs. Translate your naming to English. – Basil Bourque Jul 25 '20 at 05:59
  • 1
    If i'm on right path. You're just looking to move you this code to another java file and want to run it from same file in any other files. You can do so why define a new java class. And then call it in the file where you want to run. Learn more [here](https://www.tutorialspoint.com/java/java_methods.htm) . – CODAR747 Jul 25 '20 at 07:53

5 Answers5

1

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.

Mohammad
  • 187
  • 1
  • 12
1

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 );
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • Well i really appreciate. Explained in a good way. Let me try this :) –  Jul 25 '20 at 06:12
  • Hi, where to define xFACTOR and yFACTOR .? as i'm using swicth in java . –  Jul 25 '20 at 06:26
  • @user45154754514656210 There is no `switch` in your Question. – Basil Bourque Jul 25 '20 at 06:42
  • Yes because it is not complete code. Should i share the complete code ? –  Jul 25 '20 at 06:47
  • @user45154754514656210 No, you should keep your Question very sharply focused on one specific technical issue/problem. – Basil Bourque Jul 25 '20 at 07:44
  • The problem is how to define code in class and how to run it another activity. Can you tell me about that. Just forget about SmartObject. –  Jul 25 '20 at 07:49
  • @user45154754514656210 That was shown in the class definition and example usage calling the `calculateTopFromRog` method, in the last two code blocks in the Answer. As the heading says: Define a class, put your code into a method there. If you don’t understand defining a class and calling a method, you need to learn the basics of Java and object-oriented programming. I gave you a couple of resources to help with that. – Basil Bourque Jul 25 '20 at 07:57
  • In defined class you get value of result , What if i want to get value of result as well but value of all other variable to print or do some other caluclation there ? – CODAR747 Jul 25 '20 at 08:02
  • @user45154754514656210 That was not asked in your Question. It has been addressed in many other Questions such as: [*How to return multiple objects from a Java method?*](https://stackoverflow.com/q/457629/642706). See also the new *Records* feature previewed in Java 15. – Basil Bourque Jul 25 '20 at 08:05
0

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.

Nishit
  • 1,276
  • 2
  • 11
  • 25
0

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);
   }
}
Ayush28
  • 359
  • 3
  • 18
  • Didn't get it. Because i'm new to java. I would apreciate if you please give example by including my above code. –  Jul 25 '20 at 05:11
  • Okay....No problem.For that, clarify if you want to return any value from your code or running it for processing and returning no return value? – Ayush28 Jul 25 '20 at 05:14
  • I don't know much about returning. All i'm doing with this code is calculation. Using Bigdecimal. And final calculation will be my answer. Before final answer any calculation is passed to next variables as shown in the code above. –  Jul 25 '20 at 05:17
  • Okay,to simplify,do you want ```finallines``` value from where you called your code? – Ayush28 Jul 25 '20 at 05:20
  • Yes, I want answer from finallines that variable will provide the final answer, But all variable are answer i will will be printing all answers of all variable, but finalline will be answer –  Jul 25 '20 at 05:26
  • I have edited my answer as per your code. Upvote the answer if it works for you. Let me know if there's anything more I can help on! – Ayush28 Jul 25 '20 at 05:37
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/218563/discussion-between-user45154754514656210-and-ayush28). –  Jul 25 '20 at 07:11
0

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();
}
}
Morteza
  • 642
  • 7
  • 17