javaarraysclassmultidimensional-arraydimensional

Creating multi dimensional arrays with multiple data forms in Java


I am working on a project to help get me back into Java coding and it is a text based game (I know, not much, but I have to start somewhere). Anyway, I have come across a problem. I need to be able to put names of parts (it is a hardware tycoon game) and prices along with them into an array. For example, a desktop computer has parts such as a CPU, and the game would list your CPU choices. I need a way of storing this data, and it's pretty complicated to me because I need to not only store all of the names of CPUs for the player's benefit, but also store the prices alongside the names. On top of that, I have multiple product types such as desktops, laptops, and consoles, which each pretty much have different part names and prices. I thought of a 3 dimensional array to store the product types such as desktop (in columns), the part names (in rows), and the prices (behind the rows, if that makes sense in a 3 dimensional way. But I do not know how to initialize such an array and how to set the values on initialization.

Also, I thought of creating classes for each product type and putting arrays in each class to define parts and prices (2d arrays), but it is still complex and I would like to know how to sort this data and potentially make a system where certain parts are unlocked as game time progresses. Thank you in advance.


Solution

  • I might take you in a different direction. Why don't you create classes and objects? Then create instances of those objects? Java is an object oriented language. Creating objects would allow you to hold all of the values you need. Quick example,

    Public abstract class CPU {
    
        // Declare fields
        private float price;
        private String name;
    
        // Declare constructors 
    }
    
    Public class intelCPU extends CPU {
    
        // GetPrice
        public int getPrice() {
            return price;
        }
    
        // Set Name
        public void setName(n) {
            name = n;
        }
    
    }