0

still new to java I want to know why my code returns null and 0. it works when i scan and put it directly on the private variables. but I need to follow the UML class diagram and this is the best I could think of and Im stuck

import java.util.*;

public class cat{
    private String itemName;
    private int itemQuantity;
    private double itemPrice;
    private double amountDue;
    
    public void setItemName (String newItemName){
        this.itemName = newItemName;
    }
    public void setTotalCost (int quantity,double price){
                this.itemPrice = price;
                this.itemQuantity = quantity;
        this.amountDue = itemQuantity*itemPrice;
    }
    public String getitemName (){
        return itemName;
    }
    public double getTotalCost (){
        return amountDue;
    }
    
    public void readInput (){
        cat paws = new cat();
                Scanner scan = new Scanner(System.in);
                System.out.println("Enter the name of the item you are purchasing.");
                String newItemNames = scan.nextLine();
                paws.setItemName(newItemNames);
                System.out.println("Enter the quantity and price seperated by a space.");
                int quantities = scan.nextInt();
                double prices = scan.nextDouble();
                paws.setTotalCost(quantities,prices);
        }
    
    public void writeOutput (){
            cat spaw = new cat();
        System.out.println("You are purchasing "+itemQuantity+" "+spaw.getitemName()+ "(s) at "+itemPrice);
        System.out.println("Amount due is "+spaw.getTotalCost());
    }
    public static void main(String args[]){
        cat paw = new cat();
                paw.readInput();
                paw.writeOutput();
                
    }
} 
  • Don't create some `new cat()` in your read and write methods. You are already inside the relevant instance of `cat`, just call its methods directly, e.g `setTotalCost(quantities,prices)` instead of `paws.setTotalCost(quantities,prices)` – Arnaud Mar 02 '22 at 06:43

0 Answers0