2016-10-26 58 views
0

我正在編寫一個作業的程序,並且在運行程序時得到錯誤的計算結果。在Java中計算錯誤

我創建被設計爲採取用戶輸入來控制一個機器人,然後計算並打印出以下的程序:

  • 行駛距離
  • 水平位置
  • 垂直位置
  • 電池使用

電池使用的計算工作正常,但其餘的c計算打印值0.0或-0.0

我的代碼分佈在兩個類中,一個包含構造函數方法和所有計算,另一個包含帶代碼的主方法,以獲取用戶輸入和打印結果。

類包含構造函數和所有的計算:

class RobotMovement{ 
    private double angle; 
    private double speed; 
    private double time; 
    private double distance; 

    //Constructor method 
    public RobotMovement(double a,double s,double t){ 
     angle = a; 
     speed = s; 
     time = t; 
    } 

    //Set methods 
    public void setAngle(double a){ 
     angle = a; 
    } 
    public void setSpeed(double s){ 
     speed = s; 
    } 
    public void setTime(double t){ 
     time = t; 
    } 
    public void setDistance(double d){ 
     distance = speed * time; 
    } 

    //Get methods 
    public double getAngle(){ 
     return angle; 
    } 
    public double getSpeed(){ 
     return speed; 
    } 
    public double getTime(){ 
     return time; 
    } 
    public double getDistance(){ 
     return distance; 
    } 

    //Calculation Methods 
    public double calcHorizontal(){ 
     return distance * Math.sin(angle); 
    } 
    public double calcVertical(){ 
     return distance * Math.cos(angle); 
    } 
    public double calcBattery(){ 
     return time * Math.pow(speed,2) * 3.7; 
    } 
} 

類包含Main方法:

import java.util.*; 
class RobotUser{ 
    public static void main (String[] args){  
    Scanner scan = new Scanner(System.in); 

     //Getting user input for the Robot object 
     System.out.println("\nPlease enter the Angle, Speed and Time you wish the Robot to travel"); 

      System.out.println("\nAngle:"); 
      double angle = scan.nextDouble(); 

      System.out.println("\nSpeed:"); 
      double speed = scan.nextDouble(); 

      System.out.println("\nTime:"); 
      double time = scan.nextDouble(); 

     //Instantiates RobotMovement 
     RobotMovement Robot = new RobotMovement(angle,speed,time); 

     System.out.println("\nThe Robot moved " + Robot.getDistance() + " meters!"); 

     System.out.println("\nThe Robots horizontal position is " + Robot.calcHorizontal()); 

     System.out.println("\nThe Robots vertical position is " + Robot.calcVertical()); 

     System.out.println("\nThe Robot used " + Robot.calcBattery() + " seconds of idle time"); 



    } 
} 
+3

你從未將距離設置爲任何東西 – UnholySheep

+2

看起來你永遠不會調用'setDistance'? –

+1

你的度數是多少?因爲您調用的函數採用弧度。請參閱['Math.toRadians(double)'](https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#toRadians-double-) –

回答

0

我覺得你的問題是,你永遠不會計算行駛距離,並在Java距離變量的默認值則變爲0.0。所以當你要求計算其他3種方法的答案時,你將每個答案乘以0.0,結果就是這樣。 calcBattery是唯一不使用距離變量的人。

TLDR;只需在計算其他值之前計算距離即可。