2015-09-02 58 views
-7

嘿,我正在學習java我寫了這個簡單的代碼,我找不到任何錯誤。我無法獲得Bike2 .getTime。感謝閱讀爲什麼Bike2.getTime()返回0而不是正確的整數值?

public class ConstructorEx3 { 

     int Speed; 
     int Distance; 
     int Minute; 
     public int getTime(){ 
      return ((Distance/Speed)*Minute); 
     } 
     ConstructorEx3(){ 
      Distance = 60; 
      Speed = 30; 
      Minute = 60; 
     } 
     ConstructorEx3 (int D, int S, int M){ 
      Distance = D; 
      Speed = S; 
      Minute = M; 
     } 
     public static void main (String []arsh){ 
      ConstructorEx3 Bike1,Bike2; 
      Bike1 = new ConstructorEx3(); 
      Bike2 = new ConstructorEx3(40,80,60); 

     System.out.println("Bike one is travelling at : "+ Bike1.getTime()); 
     System.out.println("Bike two is travelling at : "+ Bike2.getTime()); 

     } 
} 
+1

你是什麼意思「我不能讓Bike2.getTime()' – Stultuske

+0

請實際上? *描述*這個問題,不要以爲我們知道這段代碼應該在做什麼或者你在運行時看到了什麼 – David

+0

@ bcsb1001:它在構造函數上方 – Stultuske

回答

4

因爲它是整數運算(40/80)*60會給你0。請注意,在整數計算40/8000.5您需要使用double值而不是int在您的程序中得到確切答案(爲您的特定情況)。

相關公約一些建議,

  • 選擇有意義的名稱爲您的類,它描述了它的目的即TimeCalculatorBike
  • 開始用小寫字母distanceDistance
  • 原路實例變量名變量名稱也應以小寫字母bike1開頭,而不是Bike1
  • 寧在構造函數中使用this.distance而不是Distance = D
+2

注意:這不是**確切的** - 這將是'BigDecimal' - 這裏只是最好的選擇,因爲額外的精度並不重要。 – bcsb1001

+0

@ bcsb1001我並不是指所有情況下*儘管*。但是,我同意這一點。 –

+1

請輸入他的代碼並修改他的編碼對話,bro – HungPV

0
Distance = 40; 
Speed = 80; 
Minute - 60; 

Distance/Speed = 0.5; 

因爲你是用int工作時,.5級聯。最後,你得到0 * Minute = 0 * 60 = 0;

最好的方法是將值轉換爲double並轉換回來。請注意,這是有損的,因爲在處理double to int轉換時,您無法獲得準確的結果。

看我怎麼在getTime()方法來解決你的問題:

public class ConstructorEx3 { 

     int Speed; 
     int Distance; 
     int Minute; 
     public int getTime(){ 
      double v = ((double)Distance/(double)Speed); 
      v= v * (double)Minute; 
      return (int)v; 
//   return ((Distance/Speed)*Minute);  
     } 
     ConstructorEx3(){ 
      Distance = 60; 
      Speed = 30; 
      Minute = 60; 
     } 
     ConstructorEx3 (int D, int S, int M){ 
      Distance = D; 
      Speed = S; 
      Minute = M; 
     } 
     public static void main (String []arsh){ 
      ConstructorEx3 Bike1,Bike2; 
      Bike1 = new ConstructorEx3(); 
      Bike2 = new ConstructorEx3(40,80,60); 

     System.out.println("Bike one is travelling at : "+ Bike1.getTime()); 
     System.out.println("Bike two is travelling at : "+ Bike2.getTime()); 

     } 
} 

輸出:

Bike one is travelling at : 120 
Bike two is travelling at : 30 
+0

謝謝布哈克辛迪我得到了答案 –

相關問題