You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java入门者求教:如何统计CD商店程序中录入的CD详情总数?

How to Count Total Number of CDs in Your CD Shop Program

Hey there! I see you're just starting out with Java and building a CD shop management program. To track how many CD entries you've created, we need to add a simple counting mechanism to your Cdshop class—right now, your class only defines CD properties but doesn't keep track of how many instances are made.

Here's how to modify your code to add this functionality:

Step-by-Step Explanation

  • Add a static variable to the Cdshop class: Static variables belong to the class itself (not individual instances), so it can keep a running total of all CDs created.
  • Increment this variable inside both of your constructors: Every time a new CD object is created, we'll add 1 to the total.
  • Add a static method to retrieve the total count: This lets you easily get the number of CDs from anywhere in your code.

Modified Code

public class Cdshop {
    int cid;
    String title;
    int price;
    String type;
    // Static variable to track total CDs
    private static int totalCds = 0;

    Cdshop() {
        cid = 100;
        title = "Avengers";
        price = 100;
        type = "Action";
        // Increment count when a CD is created with default constructor
        totalCds++;
    }

    Cdshop(int num1, String str, int num2, String str1) {
        cid = num1;
        title = str;
        price = num2;
        type = str1;
        // Increment count when a CD is created with parameterized constructor
        totalCds++;
    }

    // Static method to get the total number of CDs
    public static int getTotalCds() {
        return totalCds;
    }

    public static void main(String[] args) {
        // Create some CD instances
        Cdshop cd1 = new Cdshop();
        Cdshop cd2 = new Cdshop(101, "Frozen", 80, "Animation");
        Cdshop cd3 = new Cdshop(102, "Inception", 90, "Sci-Fi");

        // Print the total number of CDs
        System.out.println("Total number of CDs entered: " + Cdshop.getTotalCds());
    }
}

How It Works

  • The totalCds static variable starts at 0. Every time you create a new Cdshop object (whether using the default or parameterized constructor), we increment totalCds by 1.
  • The getTotalCds() static method returns the current value of totalCds, so you can access it directly using the class name (like Cdshop.getTotalCds()) without needing an instance.

When you run this code, it will output:

Total number of CDs entered: 3

That's it! This simple addition will let you keep track of how many CD entries you've created.

内容的提问来源于stack exchange,提问作者Sabaree San

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:46:55