Static Variables: Visitor Counter System
Problem Description
1. Problem Overview
This problem involves creating a system to manage visitor counts shared across multiple stores. In real-world applications, there are many situations where a single value needs to be shared across multiple locations, such as when chain store headquarters wants to know the total visitor count across all stores. In such cases, using static variables allows you to share a single value across the entire program and access or update it from anywhere.
This learning connects to the next steps of understanding static methods and class design. By understanding the concept of static variables, you gain the foundation for learning the difference between class-level data and instance-level data in object-oriented programming.
2. Prerequisites
What are static Variables?
A static variable exists once for the entire class. While regular variables (instance variables) are created anew each time an object is created, a static variable is created once when the class is loaded into memory and continues to exist until the program terminates.
For example, consider a bank account class. Each account has its own individual balance (instance variable), but the total deposits across all accounts (static variable) exists only once for the entire bank.
Why static Variables are Needed
- Data Sharing: All methods and instances can reference and update the same value
- Memory Efficiency: Sharing one variable saves memory
- Consistency Guarantee: Using the same value in multiple places maintains data consistency
How to Use Them
static variables are declared at the beginning of the class (outside methods):
static int totalVisitors = 0;
```java
This declaration creates an int variable named totalVisitors once across the entire program, initialized to 0. Methods can directly access it by name.
### <a href="https://javadrill.tech/problems/002">Scanner</a> Class for Input
The <a href="https://javadrill.tech/problems/002">Scanner</a> class reads input from the keyboard. Usage:
1. **Import**: Write "import java.util.<a href="https://javadrill.tech/problems/002">Scanner</a>;" at the top of the program
2. **Create Instance**: "<a href="https://javadrill.tech/problems/002">Scanner</a> sc = new <a href="https://javadrill.tech/problems/002">Scanner</a>(System.in);" creates a <a href="https://javadrill.tech/problems/002">Scanner</a> object
3. **Read Integer**: "int n = sc.nextInt();" reads one integer
4. **Close**: "sc.close();" releases resources when finished
### Cumulative Addition (+= <a href="https://javadrill.tech/problems/003">operator</a>)
The "+=" <a href="https://javadrill.tech/problems/003">operator</a> adds a new value to the current value and assigns the result back to the original variable.
Example:
```java
totalVisitors += 100; // Same as totalVisitors = totalVisitors + 100
```java
If totalVisitors was 300, after this line executes, totalVisitors becomes 400.
## 3. Code Explanation (Step by Step)
### Class Declaration and Static <a href="https://javadrill.tech/problems/001/001">variable declaration</a>
```java
public class VisitorCounter {
static int totalVisitors = 0;
```java
**Line 1**: Declares a public class named VisitorCounter. This class provides visitor counter functionality.
**Line 2**: Declares static variable totalVisitors and initializes it to 0. This variable is created once in memory when the program starts and is shared by all methods. At this point, the total visitor count is 0.
### Main <a href="https://javadrill.tech/problems/008">method</a> Start and Scanner Preparation
```java
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
```java
**Line 3**: Declares the main method. Program execution begins here.
**Line 4**: Creates a Scanner object and assigns it to variable sc. "System.in" represents <a href="https://javadrill.tech/problems/002/001">standard input</a> (keyboard). This allows sc to read keyboard input.
**Line 5**: Reads the first integer and assigns it to variable n. This value represents how many times to record visitor counts. For example, if n is 3, it will accept 3 inputs.
### Loop for Recording Visitor Counts
```java
for (int i = 0; i < n; i++) {
int visitors = sc.nextInt();
```java
**Line 6**: Starts a <a href="https://javadrill.tech/problems/006/001">for loop</a>. Variable i starts at 0 and repeats while less than n. This means it repeats n times. For example, if n=3, it executes for i=0, 1, 2 (3 times).
**Line 7**: Reads visitor count and assigns it to variable visitors. This value represents the number of visitors to record this time. For example, if visitors is 100, it will record 100 visitors.
### Input Validation (Error Handling)
```java
if (visitors == 0) {
System.out.println("Error: Visitor count must be at least 1");
sc.close();
return;
}
```java
**Lines 8-12**: Performs zero check. If visitor count is 0, displays error message and terminates program. Visitor count must be at least 1, so 0 is invalid. "return;" terminates the main method, stopping the program.
```java
if (visitors < 0) {
System.out.println("Error: Visitor count must be positive");
sc.close();
return;
}
```java
**Lines 13-17**: Performs negative value check. If visitor count is negative, displays error message and terminates program. Visitor count must be positive (at least 1).
```java
if (visitors > 1000) {
System.out.println("Error: Visitor count exceeds maximum (1000)");
sc.close();
return;
}
```java
**Lines 18-22**: Performs upper limit check. If visitor count exceeds 1000, displays error message and terminates program. This problem limits each record to a maximum of 1000 visitors.
### Updating Static Variable and Displaying Results
```java
totalVisitors += visitors;
System.out.println("Store added: " + visitors + " visitors");
System.out.println("Total visitors: " + totalVisitors);
```java
**Line 23**: Adds current visitor count (visitors) to static variable totalVisitors. For example, if totalVisitors is 300 and visitors is 100, after execution totalVisitors becomes 400. This line is the most important part updating the static variable.
**Line 25**: Displays the number of visitors added this time. The "+" operator concatenates strings and numbers. Example: "Store added: 100 visitors"
**Line 26**: Displays current total visitor count. Since it outputs the current value of the static variable, it shows the accumulated result. Example: "Total visitors: 400"
### Displaying Progress Bar (Visual Feedback)
```java
System.out.print("[");
int barLength = totalVisitors / 10;
for (int j = 0; j < barLength; j++) {
System.out.print("=");
}
System.out.println("]");
```java
**Line 28**: Displays "[" indicating progress bar start. Uses "print" method to display without newline.
**Line 29**: Calculates progress bar length. The total visitor count divided by 10 becomes the number of "=" symbols to display. For example, if totalVisitors is 450, barLength becomes 45.
**Lines 30-32**: Repeatedly displays "=" symbols barLength times. For loop repeats from 0 to barLength-1, displaying one "=" each time. Example: Repeating 45 times produces "============================================="
**Line 33**: Displays "]" indicating progress bar end and adds newline. This completes one line of progress bar display. Example: "[=============================================]"
### Resource Release
```java
sc.close();
```java
**Line 35**: Closes Scanner object to release resources. This is important processing to properly clean up used resources.
### Memory State Changes (Example: Input is 100, 200)
**Initial State**: totalVisitors = 0
**After 1st Input** (visitors = 100):
- totalVisitors += 100 → totalVisitors = 100
- Display: "Store added: 100 visitors" "Total visitors: 100" "[==========]"
**After 2nd Input** (visitors = 200):
- totalVisitors += 200 → totalVisitors = 300
- Display: "Store added: 200 visitors" "Total visitors: 300" "[==============================]"
This way, static variables retain previous values while accumulating new values.
## 4. Common Mistakes
### Mistake 1: Forgetting static modifier
**Wrong example**:
```java
int totalVisitors = 0; // No static!
```java
**Reason**: Without static, it becomes an instance variable. Since main method is a static method, it cannot access non-static variables. Compilation error occurs.
**Correct approach**:
```java
static int totalVisitors = 0; // Add static
```java
### Mistake 2: Using assignment instead of cumulative addition
**Wrong example**:
```java
totalVisitors = visitors; // This is assignment! Not accumulation
```java
**Reason**: This overwrites the previous value instead of accumulating. For example, if you record 100 first and then 200, totalVisitors becomes 200 instead of 300.
**Correct approach**:
```java
totalVisitors += visitors; // Use += operator for cumulative addition
```java
### Mistake 3: Forgetting to close Scanner
**Wrong example**:
```java
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// ... processing ...
// Forgot to write sc.close()!
}
```java
**Reason**: Not closing Scanner after use causes resource leaks (memory waste). While not a problem in small programs, it can cause memory shortages in large programs.
**Correct approach**:
```java
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// ... processing ...
sc.close(); // Always close
}
```java
## 5. Practical Debugging Hints
### How to Handle Errors
**1. Compilation Error: "non-static variable cannot be referenced from a static context"**
This error occurs when trying to access a non-static variable from a static method (main method). Solution is to add static modifier to the variable.
**2. Runtime Error: "InputMismatchException"**
This error occurs when nextInt() tries to read an integer but the input is not an integer. Verify input is correct.
### Debugging with println()
When program doesn't work as expected, display variable values midway for verification:
```java
System.out.println("Debug: visitors = " + visitors);
System.out.println("Debug: totalVisitors = " + totalVisitors);
```java
This confirms if variables have expected values.
### Common Error Messages
- **"';' expected"**: Missing semicolon (;)
- **"cannot find symbol"**: Spelling mistake in variable or method name
- **"incompatible types"**: Data type mismatch (e.g., trying to assign String to int)
## 6. Advanced Topics
After understanding this problem, proceed to the next steps:
### Learning Static Methods
Like static variables, static methods are shared across the entire class. For example, you can separate progress bar display into another method:
```java
static void displayProgressBar(int total) {
System.out.print("[");
int barLength = total / 10;
for (int j = 0; j < barLength; j++) {
System.out.print("=");
}
System.out.println("]");
}
```java
Calling this from main method as "displayProgressBar(totalVisitors);" makes code more readable.
### More Practical Applications
In real-world applications, static variables are used in scenarios like:
1. **Application-wide Configuration**: Constants like maximum connections or timeout limits
2. **Singleton Pattern**: Managing a single instance across the entire application
3. **Log Output**: Writing to common log file from all classes
### Performance Optimization
This program draws progress bar with loop each time, but for large numbers loops increase. A more efficient method is using String.repeat() method (Java 11+):
```java
String bar = "=".repeat(totalVisitors / 10);
System.out.println("[" + bar + "]");
```java
This approach is more concise and readable.
## 7. Related Learning Topics
Topics to learn next or concepts related to this problem:
- **Static Methods** (Category 012-002): Combine with static variables to create methods shared across the class
- **Class Design Basics** (Category 007): Learn when to use static vs instance members
- **<a href="https://javadrill.tech/problems/004">array</a> Basics** (Category 006): Efficiently manage multiple values
- **Method Division** (Category 005): Technique to divide code into reusable components
- **<a href="https://javadrill.tech/problems/019/001">exception handling</a>** (Category 019): Handle errors in more sophisticated ways.
Test Cases
※ Output examples follow programming industry standards
3 100 200 150
Store added: 100 visitors Total visitors: 100 [==========] Store added: 200 visitors Total visitors: 300 [==============================] Store added: 150 visitors Total visitors: 450 [=============================================]
2 500 300
Store added: 500 visitors Total visitors: 500 [==================================================] Store added: 300 visitors Total visitors: 800 [================================================================================]
1 1000
Store added: 1000 visitors Total visitors: 1000 [====================================================================================================]
5 1 1 1 1 1
Store added: 1 visitors Total visitors: 1 [] Store added: 1 visitors Total visitors: 2 [] Store added: 1 visitors Total visitors: 3 [] Store added: 1 visitors Total visitors: 4 [] Store added: 1 visitors Total visitors: 5 []
1 0
Error: Visitor count must be at least 1
1 -50
Error: Visitor count must be positive
1 1500
Error: Visitor count exceeds maximum (1000)
Your Solution
You have 8 free executions remaining
