In: Computer Science
Write a java program that calculates a speeding fine. The user is prompted for the speed of the vehicle, the posted speed limit and if the offence took place in the construction zone. The fine is calculated at $75 + 3$/ km over the speed limit for the first 20km over + $6 / km for the next 20 and $9/km after that. If the posted limit is 40km, the fine is doubled. If the offence took place in a construction zone, the fine is doubled as well. For example, (no construction zone involved):Speed = 77Limit = 50Fine = 75 + 20*3 + 7*6 = $177OrSpeed = 55Limit = 40Fine = (75 + 15*3) * 2 = $240Fines resulting in more than $260 produce the message “Warning, dangerous driving”.If the speed limit is exceeded more than 30km/h produce the message “Criminal offence, the court subpoena is issued?
Solution:
This problem can be solved by
using if-else constructs. The code has been provided below along
with output for different scenarios.
import java.util.*;
public class Speed
{
//Minimum function will be helpful in the calculation
public static int min_num (int a, int b)
{
if (a<b)
return a;
else
return b;
}
public static void main(String args[])
{
int fine=0;
int diff=0;
//For taking user input
Scanner reader = new Scanner(System.in);
System.out.println("Please Enter the Speed: ");
int speed = reader.nextInt();
System.out.println("Please Enter the Posted Speed Limit: ");
int speedlimit = reader.nextInt();
System.out.println("Construction Zone (y/n): ");
char zone = reader.next().charAt(0);
while (zone != 'y' && zone !='n')
{
System.out.println("Invalid Response please enter y/n : ");
System.out.println("Construction Zone (y/n): ");
zone = reader.next().charAt(0);
}
if(speed < speedlimit)
{
System.out.println("No Fine!");
}
else
{
diff = speed - speedlimit;
fine = 75 + (min_num(diff,20) * 3) ;
if ((diff - 20) > 0 )
{
fine = fine + (min_num((diff-20),20) * 6);
}
if ((diff - 40 ) > 0 )
{
fine = fine + (diff - 40) * 9;
}
if (speedlimit == 40 || zone == 'y')
{
fine = fine * 2;
}
}
System.out.println("Total Fine: $" + fine);
if (fine > 260)
{
System.out.println("Warning, dangerous driving");
}
if (diff > 30)
{
System.out.println("Criminal offence, the court subpoena is issued?");
}
}
}
Output
Please Enter the Speed:
77
Please Enter the Posted Speed Limit:
50
Construction Zone (y/n):
n
Total Fine: $177
Please Enter the Speed:
77
Please Enter the Posted Speed Limit:
50
Construction Zone (y/n):
y
Total Fine: $354
Warning, dangerous driving
Please Enter the Speed:
55
Please Enter the Posted Speed Limit:
40
Construction Zone (y/n):
n
Total Fine: $240
Please Enter the Speed:
80
Please Enter the Posted Speed Limit:
40
Construction Zone (y/n):
y
Total Fine: $510
Warning, dangerous driving
Criminal offence, the court subpoena is issued?