View Single Post
  #1 (permalink)  
Old 07-18-2007, 09:31 PM
silvia silvia is offline
Member
 
Join Date: Jul 2007
Posts: 35
silvia is on a distinguished road
Help with static variable counter
Hi, i have a pretty easy program, and i wanted to add one function - but it doesn't work. It's a little bit long,
But can you please tell me why doesn't it work?
I highlighted the problematic function. Basically it's supposed to present how many animals i've created, in this case - 4, but it gives me 0 instead.

Code:
public class Animal { //class variables String Name; int BirthYear, NumOfLegs, AYear=1970; boolean Vegetarian; public static int counter=0; Animal (String theName , int theBirthYear , int theNumOfLegs, boolean theVegetarian) { Name = theName; BirthYear = theBirthYear; NumOfLegs = theNumOfLegs; Vegetarian = theVegetarian; if (BirthYear < AYear) System.out.println( "The animal is old." ); else System.out.println( "The animal is not old." ); } //class methods public void printDetails () { System.out.println( "Name: " + Name ) ; System.out.println( "Year of birth: " + BirthYear ) ; System.out.println( "Number of legs: " + NumOfLegs ) ; System.out.println( "Vegetarian: " + Vegetarian ) ; } public static int addAnimal(){ counter=addAnimal(); return counter++; } public void walk() { System.out.println("The animal is walking in the rain."); } public void run() { System.out.println("The animal is running right now."); } public void eat() { System.out.println("The animal is busy eating"); } }
the main:
Code:
public class MainAnimalDemo { public static void main(String[] args) { //Define & initialize Animal objects : Animal Frog = new Animal ("Crazy frog", 1971, 2, true); Frog.printDetails(); Frog.run(); System.out.println(); Animal Dog = new Animal ("Bobik", 1965, 4, false); Dog.printDetails(); Dog.eat(); System.out.println(); Animal Camel = new Animal ("Moses", 2000, 2, false); Camel.printDetails(); Camel.eat(); System.out.println(); Animal Cow = new Animal ("Cow Angelika", 1954, 4, false); Cow.printDetails(); Cow.walk(); System.out.println("Current number of animals created is: " + Animal.counter); } }
Thanks
Reply With Quote
Sponsored Links