2016-10-26 87 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;只需在计算其他值之前计算距离即可。