A private Cab service company provides service within the city at the following rates: AC CAR NON AC CAR UPTO 5 KM Rs. 150/- Rs. 120/- BEYOND 5 KM Rs. 10/- PER KM Rs. 08/- PER KM Design a class CabService with the following description: Member variables / data members: String car_type - To store the type of car (AC or NON AC) double km - To store the kilometer travelled double bill - To calculate and store the bill amount Member methods: CabService() - Default constructor to initialize data members. String data members to "" and double data members to 0.0. void accept() - To accept car_type and km (using Scanner class only). void calculate()- To calculate the bill as per the rules given above. void display() - To display the bill as per the following format: CAR TYPE: KILOMETER TRAVELLED: TOTAL BILL: Create an object of the class in the main method and invoke the member methods.
Topic: Class with default constructor and slab billing
Answer
import java.util.Scanner;
class CabService { String car_type; double km, bill;
CabService() { car_type = ""; km = 0.0; bill = 0.0; }
void accept() { Scanner sc = new Scanner(System.in); System.out.print("Enter car type (AC / NON AC) : "); car_type = sc.nextLine(); System.out.print("Enter kilometres travelled : "); km = sc.nextDouble(); }
void calculate() { if(car_type.equalsIgnoreCase("AC")) { if(km <= 5) bill = 150; else bill = 150 + (km - 5) * 10; } else { if(km <= 5) bill = 120; else bill = 120 + (km - 5) * 8; } }
void display() { System.out.println("CAR TYPE: " + car_type); System.out.println("KILOMETER TRAVELLED: " + km); System.out.println("TOTAL BILL: " + bill); }
public static void main(String args[]) { CabService ob = new CabService(); ob.accept(); ob.calculate(); ob.display(); } }
Two things make this question different from an ordinary slab calculation.
First, the constructor is EXPLICITLY required, with stated initial values. Write CabService() with no return type (not even void) and assign "" to the String and 0.0 to the doubles exactly as the question says. Omitting it loses marks even though Java would supply defaults anyway.
Second, the rates form a two-way table: the car type chooses the column, the distance chooses the row. So the natural structure is an if-else on car_type with a nested if-else on km inside each branch.
The charge beyond 5 km is cumulative: the flat Rs. 150 covers the first 5 km and only the EXTRA kilometres are charged at Rs. 10. Hence 150 + (km - 5) * 10, never km * 10.
Compare Strings with equalsIgnoreCase() rather than ==, so that "ac", "AC" and "Ac" are all accepted.
Check: an AC car for 12 km gives 150 + 7 x 10 = Rs. 220; a non-AC car for 10 km gives 120 + 5 x 8 = Rs. 160.
car_type String - type of car, AC or NON AC km double - kilometres travelled bill double - total amount payable sc Scanner - object used to read input ob CabService - object of the class used in main()