我正在为作业编写程序,并在运行程序时得到错误的计算。
我创建的程序旨在获取用户输入来控制机器人,然后计算并打印出以下内容:
电池使用计算工作正常,但其余计算打印值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;
}
}
包含主要方法的类:
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");
}
}
答案 0 :(得分:0)
我认为你的问题是你永远不会计算行进的距离,而在java中,距离变量的默认值则变为0.0。因此,当您要求计算其他3种方法的答案时,您将每个答案乘以0.0,这就是您最终得出这些结果的方式。 calcBattery是唯一一个不使用距离变量的人。
TLDR;在你要求计算其他值之前计算距离。