Advertisement
SenpaiZero

LabExer2 Class

Feb 19th, 2024
611
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.57 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class LabExer2 {
  4.    
  5.     // Creating private variable for encapsulation
  6.     private String itemName;
  7.     private Double itemPrice;
  8.     private int itemQuantity;
  9.     private double amountDue;
  10.    
  11.     // Creating setter for itemName variable
  12.     public void setItemName(String newItemName)
  13.     {
  14.         itemName = newItemName;
  15.     }
  16.     // Creating setter for total or amountDue variable
  17.     public void setTotalCost(int quantity, double price)
  18.     {
  19.         itemQuantity = quantity;
  20.         itemPrice = price;
  21.        
  22.         amountDue = (itemQuantity * itemPrice);
  23.     }
  24.    
  25.     // Creating getter for itemName variable
  26.     public String getItemName()
  27.     {
  28.         return itemName;
  29.     }
  30.    
  31.     // Creating getter for totalCost or amountDue variable
  32.     public Double getTotalCost()
  33.     {
  34.         return amountDue;
  35.     }
  36.    
  37.     // Read input method for the main class but the method should be inside the main class
  38.     // since the encpasulation will be useless
  39.     public void readInput()
  40.     {
  41.         Scanner scanner = new Scanner(System.in);
  42.         System.out.println("Enter the name of the item you are purchasing.");
  43.         setItemName(scanner.nextLine());
  44.        
  45.         System.out.println("Enter the quantity and price separated by a space.");
  46.         setTotalCost(scanner.nextInt(), scanner.nextDouble());
  47.     }
  48.    
  49.     // output method for the main class but just like the read input, it should not be
  50.     // in the same class as encapsulated variable
  51.     public void writeOutput()
  52.     {
  53.         System.out.println("You are purchasing " + itemQuantity + " " + getItemName()
  54.         + "(s) at " + itemPrice + " each.");
  55.         System.out.println("Amount due is " + getTotalCost());
  56.     }
  57.    
  58. }
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement