Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
February 3rd, 2013, 04:25 PM
 mcrocker94
Registered User

Join Date: Feb 2013
Posts: 2
Time spent in forums: 5 m 34 sec
Reputation Power: 0
Homework - 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
February 3rd, 2013, 05:50 PM
 NormR
Contributing User

Join Date: Aug 2010
Location: SW Missouri
Posts: 3,588
Time spent in forums: 2 Weeks 3 Days 3 h 15 m 46 sec
Reputation Power: 347
Can you explain what problems you are having? Post the code and ask your questions about it.

#3
February 3rd, 2013, 11:22 PM
 mcrocker94
Registered User

Join Date: Feb 2013
Posts: 2
Time spent in forums: 5 m 34 sec
Reputation 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.

#4
February 4th, 2013, 04:17 AM
 Aurum84
Contributing User

Join Date: Nov 2012
Posts: 74
Time spent in forums: 3 Days 23 h 19 m 57 sec
Reputation Power: 18
Quote:
 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());

}
}```

 Viewing: Dev Shed Forums > Programming Languages > Java Help > Homework - Small Java Question about counters!