我有一项任务要编写一个程序,该程序将采用用户输入的速度和小时数来查找距离。我有一个带有计算方法的类,但需要使用 for 循环来输出一个表格,该表格将显示用户输入的每个小时的旅行小时数,如下所示:
小时距离
1 10 2 20 3 30 等
首先,我编写了类来进行计算,但是当我将 for 循环放在一起时,计数器出现错误。
这是具有计算距离的方法的对象类。
package distancetraveled;
public class DistanceTraveled {
private double speed; //speed
private int hours; //hours
private double distance; //distance
//distanceTravelled constructor
public DistanceTraveled(double s, int h) {
speed = s;
hours = h;
}
// findDistance method
public double findDistance() {
distance = speed * hours;
return distance;
}
// setSpeed method
public void setSpeed(double s) {
s = speed;
}
// set distance method
public void setDistance(int h) {
h = hours;
}
// getSpeed method
public double getSpeed() {
return speed;
}
//getDistance method
public double getDistance() {
return distance;
}
}
以及显示表格的程序:
package distancetraveled;
import java.util.Scanner;
public class DistanceTraveledTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double testSpeed;
int testHours;
System.out.println("What is the speed of the vehicle?");
testSpeed = input.nextDouble();
while (testSpeed <= 1){
System.out.print("The speed must be equal to or greater than one");
System.out.println("What is the speed of the vehicle?");
testSpeed = input.nextDouble();
}
System.out.println("How many hours has the vehicle been travelling?");
testHours = input.nextInt();
while (testHours <= 1){
System.out.print("The hours must be equal to or greater than one");
System.out.println("How many hours has the vehicle been traveling?");
testHours = input.nextInt();
}
DistanceTraveled traveller = new DistanceTraveled(testSpeed, testHours);
System.out.println("Hour\t\tDistance Travelled");
System.out.println("------------------------------");
for(i=0;i<=testHours;i++){
System.out.print(testHours + "\t\t" + traveller.findDistance());
}
}
}
我敢肯定还有很多其他错误。谢谢大家和任何人。