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!
new TestJNIPrimitive().average(3,2);calls your function. You call it twice, it gets called twice.