#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    2
    Rep Power
    0

    Small Java Question about counters!


    I have an assignment I have just started that is quite easy, yet I am getting hung up on a small detail. We have to create a Policy class, and there are variables for the policy Number and the amount. Then you create a static variable that increases by one. Then you create a print method, and when it prints them out, the policy number increases by one like the counter. This is my code, the variables and constructor, but even after fooling around with them for 30 minutes, I always get zeroes or ones.
    Thanks for the help!

    public class Policy {
    float amount;
    int policyNum;
    int counter;
    public Policy(float a){
    counter = counter + 1;
    amount = a;
    policyNum = counter;
    }
  2. #2
  3. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,713
    Rep Power
    348
    Can you explain what problems you are having? Post the code and ask your questions about it.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    2
    Rep Power
    0
    In my test code, I am declaring 3 policies, and I want their policy num to be 1 2 and 3. They always end up all ones or all zeroes.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    74
    Rep Power
    18
    Originally Posted by mcrocker94
    In my test code, I am declaring 3 policies, and I want their policy num to be 1 2 and 3. They always end up all ones or all zeroes.
    There are 2 solutions here:
    In your text, there is spoken of a static variable. However in your code there is none. So: declare it static.

    The other solution is to have the counting of the policy objects and the assignation of the count not handled by the policy object but by another class that is acts as a collection of policies. Call it for example, a PolicyCollection.

    The code for solution 1 is this:

    Code:
    public class Policy {
    	float amount;
    	int policyNum;
    	static int counter;
    	
    	public Policy(float a){
    	counter = counter + 1;
    	amount = a;
    	policyNum = counter;
    	}
    	
    	public String toString()
    	{
    	
    		return "policyNumber " + policyNum + ", amount " + amount + " , counter: " + counter;
    	}
    }
    
    class PolicyMain
    {
    
    	public static void main(String[] args)
    	{
    		Policy p1 = new Policy(1.0f);
    		System.out.println(p1.toString());
    		Policy p2 = new Policy(2.0f);
    		System.out.println(p2.toString());
    
    
    	}
    }

IMN logo majestic logo threadwatch logo seochat tools logo