Milo StaKic Milo StaKic - 1 month ago 10
Java Question

How to Properly Increment Static Variable?

Here is the method in the driver:

public class CustomerTest {

private static int customerCounter = 0;

public static boolean test1(){
System.out.println("Test1: create a customer");
Customer c = new Customer("Alice", "Smith");
customerCounter++;
return c.getName().equals("Alice Smith") && customerCounter == c.getCustomerID();
}

public static boolean test2() {
System.out.println("Test2: create two customers");
Customer c1 = new Customer("Alice", "Smith");
Customer c2 = new Customer("Bob", "Simpson");
customerCounter += 2;
return c1.getName().equals("Alice Smith") && (customerCounter - 1) == c1.getCustomerID()
&& c2.getName().equals("Bob Simpson") && (customerCounter) == c2.getCustomerID();
}

public static void main(String[] args) {
String result = "";
//System.out.print("Test 1: ");
result = test1() ? "pass." : "failed.";
System.out.println(result);
//System.out.print("Test 2: ");
result = test2() ? "pass." : "failed.";
System.out.println(result);
}
}


Here is code I've written:

public class Customer {

public static final int MAX_ACCOUNTS = 5;

private String firstName;
private String lastName;
private int customerID;
private BankAccount[] accounts;
private int numAccounts;
private static int nextCustomerID = 1;

//default constructor
public Customer() {
firstName = "";
lastName = "";
customerID = 1;
accounts = null;
numAccounts = 0;
nextCustomerID = 1;
}

//Constructor sets name and initialized values
//@param first is the first name
//@param last is the last name
public Customer (String first, String last)
{
this.firstName = first;
this.lastName = last;
this.customerID = 1;
Customer.nextCustomerID = 1;

}

public String getFirst(){
return firstName;

}
public String getLast(){
return lastName;
}


public String getName ()
{
return String.format("%s,%s", getFirst(),getLast());

}
public int getCustomerID ()
{
return customerID;

}

}


When I run the driver it returns failed for test 2.I think its because I am improperly incrementing my nextCustomerID.

Answer

You never increment nextCustomerId. It's a private variable, so it can only change within Customer, and the only place you reference it is to assign it the value 1.

The following two lines of your constructor are incorrect:

this.customerID = 1;
Customer.nextCustomerID = 1;

Replace these with:

this.customerID = nextCustomerId;
nextCustomerID++;

(You should also update your default constructor in a similar fashion).

The ++ operator increments the variable's value by 1.

The = operator is a simple assignment operator, and simply sets the variable on the left-hand side to the value on the right-hand side.

It'll be worthwhile to review the Java Introduction to Assignment and Unary operators.