James James - 1 month ago 5
Java Question

How do I use a simple counter in arrays format?

I am completely new to Java and I am trying to teach myself the way around the concept of arrays however, I am having difficultly truly understanding it.

For example, if I have four separate counters (or four separate variables that need a counter associated with it), how can I use an array in this case?

Maybe there is a special "equation" or format already out there for counters in array format, but I am unaware.

Thank you in advance.




Additional information:

I have a program that I am trying to use that will keep track of different hotels.
For example anytime someone wants to stay there, the program is supposed to keep a count of that. There are four different types. I want to try to do this in arrays, because based on my research it makes the most sense, but I am unaware how to even begin, which is why I do not have an code as of right now.

Answer

If I understand, you want an array keeping track of four different "hotels" and the guest count:

int[] hotels = {0, 0, 0, 0}; // Declare array with 4 empty values

// Add person to hotel #1
++hotels[0]; // Array indexes start at 0

// Use loop to access every index of array and perform a task each time
for(int i = 0; i < hotels.length; i++){
    System.out.println("Hotel #" + i + " has " + hotels[i] + " guests.");
}

For more flexibility, you can use ArrayList, because there is no limit on length:

ArrayList<Integer> hotels = new ArrayList<Integer>(4); // Declare array with 4 empty values

// Add person to hotel #1
hotels.set(0, ++hotels.get(0)); // Array indexes start at 0

// Use loop to access every index of array and perform a task each time
for(int i = 0; i < hotels.size(); i++){
    System.out.println("Hotel #" + i + " has " + hotels.get(i) + " guests.");
}