Write a program to input speed in mph and time in hours and

Write a program to input speed (in mph) and time (in hours) and calculate distance = speed * time. Sample data: if the user enters a speed of 65 mph and a time of 1.25 hours then distance = 81.25 miles Use input validation to make sure speed and time are positive.

Solution

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package chegg;

import java.util.Scanner;


public class Distance {


public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double speed,time;
System.out.print(\"Please enter speed in mph : \");
speed = input.nextDouble();
  
while(speed<=0)
{
System.out.print(\"Please enter speed in mph : \");
speed = input.nextDouble();
}
  
System.out.print(\"Please enter time in hours : \");
time = input.nextDouble();
  
while(time<=0)
{
System.out.print(\"Please enter time in hours : \");
time = input.nextDouble();
}
  
double distance = speed*time;
  
System.out.println(\"Distance for speed \" + speed + \" mph in time \"+time+\" hours is : \"+distance+\" miles.\");
}
}

OUTPUT:

run:
Please enter speed in mph : -1
Please enter speed in mph : 65
Please enter time in hours : -2
Please enter time in hours : 1.25
Distance for speed 65.0 mph in time 1.25 hours is : 81.25 miles.
BUILD SUCCESSFUL (total time: 6 seconds)

 Write a program to input speed (in mph) and time (in hours) and calculate distance = speed * time. Sample data: if the user enters a speed of 65 mph and a time

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site