Cannot make an updatable variable in java

Viewed 54

So here's my code :

public class Shoe {
    String brandName;
    double shoePrice;
    int shoesInStock;

    double totalRevenue;

    public Shoe(String name, double price, int shoesAvailable){
        brandName = name;
        shoePrice = price;
        shoesInStock = shoesAvailable;
    }

    public void shoeSold(){
        totalRevenue = totalRevenue + shoePrice;
        System.out.println("Your new total revenue is " + totalRevenue + "$");
    }

    public static void main(String[] args){
        Shoe yeezy = new Shoe("adidas", 75, 10);
        Shoe airforce = new Shoe("nike", 140, 15);

        yeezy.shoeSold();
        airforce.shoeSold();
    }
}

Output :

Your new total revenue is 75.0$
Your new total revenue is 140.0$

Why am I not able to make the totalRevenue variable update and not return to 0 each time, I'm new to java and this was quite an easy task in python I know that java is an oop language but is there no way to make a variable store the value and not return to 0 ? Thanks in advance !

1 Answers

To quickly fix the issue, you can just mark totalRevenue as static. Although your code lacks many basic coding practices that you need to learn and improve your code.

working code:

public class Shoe {
    String brandName;
    double shoePrice;
    int shoesInStock;

    static double totalRevenue;

    public Shoe(String name, double price, int shoesAvailable){
        brandName = name;
        shoePrice = price;
        shoesInStock = shoesAvailable;
    }

    public void shoeSold(){
        totalRevenue = totalRevenue + shoePrice;
        System.out.println("Your new total revenue is " + totalRevenue + "$");
    }

    public static void main(String[] args){
        Shoe yeezy = new Shoe("adidas", 75, 10);
        Shoe airforce = new Shoe("nike", 140, 15);

        yeezy.shoeSold();
        airforce.shoeSold();
    }
}
Related