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
Cdshopclass: 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
totalCdsstatic variable starts at 0. Every time you create a newCdshopobject (whether using the default or parameterized constructor), we incrementtotalCdsby 1. - The
getTotalCds()static method returns the current value oftotalCds, so you can access it directly using the class name (likeCdshop.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
相关产品推荐
相关产品推荐

