In: Computer Science
Using a Java.
2. Write a Java program calculate_fare.java to take the input for number of miles, and the class of journey (1,2, or 3, for first, second, and third class respectively), for a train journey.
The program should then calculate and display the fare of
journey based on the following criteria:
Note: Use Switch...case and if...else
construct
First (1) Class |
Second (1) Class |
Third (3) Class |
|
First 100 mile |
$ 3 per mile |
$ 2 per mile |
$ 1.50 per mile |
Next 150 mile |
$ 2.50 per mile |
$ 1.50 per mile |
$ 1 per mile |
Remaining |
$ 2 per mile |
$ 1 per mile |
$ 0.50 per mile |
Rubric:
- Input, usage of appropriate data types - 2 points
- Appropriate usage of if...else in each case of switch construct
for each class of journey : 4 points
- Documentation and appropriate variable names- 2 points
The layout of switch case should be as follows:
switch(cls)//class
{
case 1: if construct for calculating fare for class 1
case 2: if construct for calculating fare for class 2
case 3: if construct for calculating fare for class 3
default: Display it is an invalid class
}
If you have any doubts, please give me comment...
import java.util.Scanner;
public class calculate_fare {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.print("Enter number of miles: ");
int miles = scnr.nextInt();
System.out.print("Enter class of journey: ");
int cls = scnr.nextInt();
double fare = 0.0;
switch (cls) {
case 1:
// for first 100 miles
if (miles <= 100)
fare = miles * 3.00;
else {
fare = 100 * 3.00;
// next 150 miles
if ((miles - 100) <= 150)
fare += (miles - 100) * 2.50;
else {
fare += 150 * 2.50;
// remaining
fare += (miles - 250) * 2.00;
}
}
System.out.println("Total fare is: " + fare);
break;
case 2:
// for first 100 miles
if (miles <= 100)
fare = miles * 2.00;
else {
fare = 100 * 2.00;
// next 150 miles
if ((miles - 100) <= 150)
fare += (miles - 100) * 1.50;
else {
fare += 150 * 1.50;
// remaining
fare += (miles - 250) * 1.00;
}
}
System.out.println("Total fare is: " + fare);
break;
case 3:
// for first 100 miles
if (miles <= 100)
fare = miles * 1.50;
else {
fare = 100 * 1.50;
// next 150 miles
if ((miles - 100) <= 150)
fare += (miles - 100) * 1.00;
else {
fare += 150 * 1.00;
// remaining
fare += (miles - 250) * 0.50;
}
}
System.out.println("Total fare is: " + fare);
break;
default:
System.out.println("Invalid class");
}
}
}