1

I have a Java file that declares a native method average() which is defined in my C file. The method takes the average of two numbers, prints "In C, the numbers are n1, n2" (n1 and n2 being the input numbers), and returns the average as a double.

The Java file then calls the average() method, prints "In Java, the average is (n1 + n2)/2" and then prints the average x 2.

Here is an example with the numbers 3 and 2 (running my Java file):

In C, the numbers are 3 and 2

In Java, the average is 2.5

In C, the numbers are 3 and 2

5.0

I would like to multiply only the return value from the C file (the average value) by 2. I don't want the string "In C, the numbers are 3 and 2" to print again. How can I print only the return value (average) from the C file and not have the string "In C, the numbers are 3 and 2" print again? I know I can just create another method but that would be very repetitive.

My Java file follows:

public class TestJNIPrimitive {
    
    static {
        System.loadLibrary("myjni"); //myjni.dll (Windows)
    }

    private native double average(int n1, int n2);
    public static void main(String args[]) {
        
        System.out.println("In Java, the average is " + new TestJNIPrimitive().average(3,2));
        double result = new TestJNIPrimitive().average(3,2);
        System.out.println(result*2);
    }
}

My C file follows:

JNIEXPORT jdouble JNICALL Java_TestJNIPrimitive_average(JNIEnv *env, jobject thisObj, jint n1, jint n2) {
    
    printf("In C, the numbers are %d and %d\n", n1, n2);
    jdouble result;
    result = ((jdouble)n1 + n2) / 2.0;
    // jint is mapped to int, jdouble is mapped to double
    return result;
}

Thanks for the help!

2
  • 1
    How about adding a 3rd parameter? (which allows to suppress this line from being printed) Commented Jul 22, 2015 at 23:22
  • new TestJNIPrimitive().average(3,2); calls your function. You call it twice, it gets called twice. Commented Jul 22, 2015 at 23:23

1 Answer 1

5

Unless I'm missing something, you can simply not call your C average function twice, and just store the result after you call it once:

public static void main(String args[]) {
    double result = new TestJNIPrimitive().average(3,2);
    System.out.println("In Java, the average is " + result);
    System.out.println(result*2);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.