Home > Mobile >  How to fix this NaN
How to fix this NaN

Time:10-17

I am trying to do Java Native Interface which is using the gcc to compile the c file and the java code is

import java.util.Scanner;

class BMICalculator {

double weight, height;
native double BMIcalculate();

static {
    System.loadLibrary("Calculate");
}
public static void main(String args[]){
                      
            Scanner input = new Scanner(System.in);
            BMICalculator total = new BMICalculator();
                
            System.out.printf("Enter your weight : ");
            total.weight = input.nextDouble();
            System.out.printf("Enter your height : ");
            total.height = input.nextDouble();

            System.out.println("Your BMI is "   total.BMIcalculate());
                
        }

    }            

And the .c file is :

#include <jni.h>
#include <math.h>


JNIEXPORT jdouble JNICALL Java_BMICalculator_BMIcalculate(JNIEnv *env, jobject obj){
    
    jdouble total, weight1, height1 ;
    jfieldID fid1, fid2;
        
    jclass cls = (*env)->GetObjectClass(env,obj);
    fid1 = (*env)->GetFieldID(env,cls,"weight","D");
    fid2 = (*env)->GetFieldID(env,cls,"height","D");
    
    if((fid1 == NULL) || (fid2 == NULL)) return 0;
    
    
    weight1 = (*env)->GetDoubleField(env,obj,fid1);
    height1 = (*env)->GetDoubleField(env,obj,fid2);

    weight1 = (*env)->GetIntField(env,obj,fid1);
    height1 = (*env)->GetIntField(env,obj,fid2);
    
    
    
    height1 = height1 / 100;
    
    total = weight1 / ( height1 * height1 );    

        return total;
    
    
}

I am not sure whether is the function in .c file got problem or is my java code because the output that I get is enter image description here

How do i fix the output NaN

CodePudding user response:

weight1 = (*env)->GetDoubleField(env,obj,fid1);
height1 = (*env)->GetDoubleField(env,obj,fid2);

weight1 = (*env)->GetIntField(env,obj,fid1);
height1 = (*env)->GetIntField(env,obj,fid2);

What are the second batch of lines doing there? fid1 and fid2 are field ids of double fields, so GetDoubleField is how one should read them. GetIntField results in unspecced results. Just delete the second batch of lines.

NB: If this is just teaching yourself JNI, good job. If this is because you think it'll be 'faster', no it won't be, the JVM is excellent at hotspotting this kind of code. This is just hard to read and a lot slower (JNI bridging is definitely not free).

  • Related