Having trouble with a java assignment This is the Question : The distance a vehi
ID: 3673329 • Letter: H
Question
Having trouble with a java assignment This is the Question : The distance a vehicle travels can be calculated as follows: Distance = Speed * Time For example, if a train travels 40 miles per hour (mph) for three hours. The distance traveled is 120 miles or 40 * 3 = 120 Design a class called Distance whose constructor accepts two arguments. The speed of a vehicle (in miles per hour) and the number of hours it has traveled represented as a variable called time. Besides the appropriate gets (accessors) and sets (mutators), it should have a method named getDistance that returns the distance, in miles that the vehicle has traveled. Demonstrate the class in a main program called DistanceDemoFirstName that uses a while loop (period < = time) to display the distance a vehicle has traveled for each hour of a time period specified by the user. For example, if a vehicle is traveling at 40 mph for a three-hour time period, it should display a report similar to the one shown here. Hour Distance Traveled 1 40 2 80 3 120 Input Validation: Do not accept a negative number for speed, and do not accept any value less than one for time traveled (use a while loop to test for speed > = 0, and another while loop to test for time > 1). note* there should be 3 while loops. Any thoughts at all would be great.
Explanation / Answer
// Distance.java
public class Distance {
private int speed;
private int time;
public Distance(int speed, int time) {
this.speed = speed;
this.time = time;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
public int getDistance(){
return time*speed;
}
}
//DistanceDemoFirstName.java
import java.util.Scanner;
class DistanceDemoFirstName{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int speed;
int time;
// asking for speed
System.out.print("Enter speed (>=0): ");
speed = sc.nextInt();
while(speed < 0){
System.out.print("Enter speed (>=0): ");
speed = sc.nextInt();
}
// asking for time
System.out.print("Enter time (>=1): ");
time = sc.nextInt();
while(time < 1){
System.out.print("Enter time (>=1): ");
time = sc.nextInt();
}
sc.close();
// Creating Distance Object
Distance d = new Distance(speed, time);
// printing distance travelled per hour
for(int i=1; i<=d.getTime(); i++){
int distance = i*d.getSpeed();
System.out.print(i+" "+distance+" ");
}
System.out.println();
}
}
/*
Output:
Enter speed (>=0): 40
Enter time (>=1): 4
1 40 2 80 3 120 4 160
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.