Define a class named CloudStorage with the following specifications: Member Variables: int acno - stores the user’s account number. int space - stores the amount of storage space in GB purchased by the user. double bill - stores the total price to be paid by the user. Member Methods: void accept() - prompts the user to input their account number and storage space using Scanner class methods only. void calculate() - calculates the total price based on the storage space purchased using the pricing table provided: Storage range Price per GB (Rs) First 15 GB 15 Next 15 GB 13 Above 30 GB 11 void display() - displays the account number, storage space and bill to be paid. Write a main method to create an object of the class and invoke the methods of the class with respect to the object.
Topic: Class with menu-driven slab calculation
Answer
import java.util.Scanner;
class CloudStorage { int acno; // user’s account number int space; // storage space purchased, in GB double bill; // total price payable
void accept() { Scanner sc = new Scanner(System.in); System.out.print("Enter account number : "); acno = sc.nextInt(); System.out.print("Enter storage space in GB : "); space = sc.nextInt(); }
void calculate() { if(space <= 15) bill = space * 15; else if(space <= 30) bill = 15 * 15 + (space - 15) * 13; else bill = 15 * 15 + 15 * 13 + (space - 30) * 11; }
void display() { System.out.println("Account Number : " + acno); System.out.println("Storage Space : " + space + " GB"); System.out.println("Bill Amount : Rs. " + bill); }
public static void main(String args[]) { CloudStorage ob = new CloudStorage(); ob.accept(); ob.calculate(); ob.display(); } }
This is a slab-rate question, the commonest pattern in Section A of the class-definition questions. The whole difficulty is in calculate().
The slabs are cumulative, not flat. A user buying 40 GB does not pay 40 x 11 — the first 15 GB are charged at 15, the next 15 at 13, and only the remaining 10 at 11. So each branch must add the charges of the full slabs below it: space <= 15 : space x 15 16 to 30 : 225 + (space - 15) x 13 above 30 : 225 + 195 + (space - 30) x 11 Check with 40 GB: 225 + 195 + 110 = Rs. 530.
Order the conditions from smallest to largest. Because else-if stops at the first true test, reaching the second branch already guarantees space is above 15, so you never need to write (space > 15 && space <= 30).
Two marks are commonly lost here: declaring the Scanner outside accept() (the question says to read inside that method), and writing the slabs as flat rates. Note also that bill is a double while the rates are ints — Java promotes the result automatically, so the answer prints as 530.0.
acno int - account number entered by the user space int - storage space in GB entered by the user bill double - total amount payable, computed slab-wise sc Scanner - object used to read input from the keyboard ob CloudStorage - object of the class used in main()