2015-12-01 37 views
-1

我很新的編程和我目前教自己的Java。我試圖製作一個涉及BMI的程序,但我繼續顯示0而不是BMI值。Java - 數學與整數

我敢肯定我的錯誤是在數學,但我不知道是什麼改變:

public class bmi { 
    public static void main(String[] args) { 
     Scanner k = new Scanner(System.in); 

     System.out.print("Weight(kg):"); 
     int weight=k.nextInt(); 

     //now for the second scanner or int 
     Scanner j = new Scanner(System.in); 
     System.out.print("Height (m):"); 

     int height=j.nextInt(); 
     double bodyMassIndex = ((double) weight/(height * height)); 

     //so far this looks fine i believe , however there might be a problem with the math. 
     System.out.println(bodyMassIndex); 
    } 
} 
+1

整數除法正在截斷。使重量和高度變量加倍。 –

回答

1

更改爲double bodyMassIndex = (703 * ((double) weight/(height * height)));

編輯:

public class bmi 
{ 
    public static void main(String[] args) 
    { 
     Scanner input = new Scanner(System.in); // Only need one scanner for multiple variables 

     System.out.print("Weight(kg):"); 
     double weight = input.nextDouble(); 

     System.out.print("Height (m):"); 
     double height = input.nextDouble(); 

     double bodyMassIndex = (weight/(height * height)); 

     System.out.println(bodyMassIndex); 
    } 
} 
+0

謝謝。你能告訴我爲什麼我得到一個「線程中的異常」主java.util.InputMismatchExcpetion錯誤? (請參閱編輯原始帖子的代碼) – imp

+0

我會在我編輯的帖子中發佈類似於我所說的代碼。 –