【发布时间】:2021-11-06 19:07:37
【问题描述】:
我得到了部分完成的代码来完成,但我不知道下一步该做什么。
该程序要求用户输入以确定行驶距离。
我填写了大部分代码,但我似乎不知道还要添加什么才能使 getDistance() 起作用。
有人可以给我一个建议吗?
说明如下:
车辆行驶的距离可以计算如下: 距离 = 速度 * 时间 例如,如果火车以每小时 40 英里的速度行驶三个小时,则行驶距离为 120 英里。编写一个程序,询问车辆的速度(以英里/小时为单位)和已行驶的小时数。它应该使用循环来显示车辆在用户指定的时间段内每小时行驶的距离。例如,如果一辆车以 40 英里/小时的速度行驶了三个小时,它应该显示类似于以下报告的报告:行驶距离小时
//Distance.java
public class Distance
{
private double speed; // The vehicle speed
private int hours; // The hours traveled
/**
* The constructor initializes the object
* with a vehicle speed and number hours
* it has traveled.
*/
public Distance(double s, int h)
{
}
/**
* The setSpeed method sets the vehicle's
* speed.
*/
public void setSpeed(double s)
{
speed = s;
}
/**
* The setHours method sets the number of
* hours traveled.
*/
public void setHours(int h)
{
hours = h;
}
/**
* The getSpeed method returns the speed
* of the vehicle.
*/
public double getSpeed()
{
return speed;
}
/**
* The getHours method returns the number
* of hours traveled by the vehicle.
*/
public int getHours()
{
return hours;
}
/**
* The getDistance method returns the
* distance traveled by the vehicle.
*/
public double getDistance()
{
return speed * hours;
}
}
//DistanceDemo.java
public class DistanceDemo
{
public static void main(String[] args)
{
double speed; // Vehicle's speed
int maxHours; // Number of hours
int period; // Counter for time periods
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Get the speed.
System.out.print("Enter the vehicle's speed: ");
speed = keyboard.nextDouble();
// Validate the speed.
while (speed < 1)
{
System.out.println("Enter a valid speed: ");
speed = keyboard.nextDouble();
}
// Get the number of hours.
System.out.print("Enter the number of hours the " +
"vehicle was in motion: ");
maxHours = keyboard.nextInt();
// Validate the hours.
while (maxHours < 1)
{
System.out.println("Enter a vaid time");
maxHours = keyboard.nextInt();
}
// Display the table header.
System.out.println("Hour\tDistance Traveled");
System.out.println("----------------------------------");
// Display the table of distances.
period = 1;
while (period <= maxHours)
{
// Create a Distance object for this period.
Distance d = new Distance(speed, period);
// Display the distance for this period.
System.out.println(period + "\t\t" + d.getDistance());
// Increment period.
period++;
}
}
}
【问题讨论】:
-
当前输出的是什么?
-
此时您最好回顾一下 Java 中的方法是如何工作的。尝试注意方法参数/参数的概念。大量提示:您有一个不向其传递任何参数的 getDistance 方法,那么您希望它如何工作?
-
此时您可能需要学习如何调试您的代码。听说有一些资源可供阅读/使用:Rubber Duck Debugging 和 How to debug small programs 还有许多 IDE 特定的调试教程。
-
糟糕的标题。重写以总结您的具体技术问题。
标签: java