I feel like this is right, but is it? I always get 1 when I run it.
public class Cat {
private static int catCount = 0;
public static void addNewCat() {
//write your code here
Cat cat = new Cat();
catCount++;
}
public static void main(String[] args) {
Cat.addNewCat();
System.out.println(catCount);
}
}
Is this right?
Under discussion
Comments (7)
- Popular
- New
- Old
You must be signed in to leave a comment
Sherlockk
5 June 2020, 13:24
Actually just catCount++; will be enough:
public static void addNewCat(){
catCount++;
}
Main:
public static void main(String[] args){
addNewCat();
addNewCat();
addNewCat();
System.out.println(Cat.catCount);
}
0
MaGaby2280
12 September 2019, 17:34
It is easier if you just add this:
public static void addNewCat() {
int addNewCat = catCount ++;
}
0
M Harsha Vinay
29 May 2019, 06:17
package com.codegym.task.task04.task0404;
/*
Cat register
*/
public class Cat {
private static int catCount = 0;
public static void addNewCat() {
int h=1;
catCount+=h;
System.out.println(catCount);
h++;
//write your code here
}
public static void main(String[] args) {
addNewCat();
addNewCat();
addNewCat();
}
}
here i called 3 times and i got incremented 3 times .....i.e.. i printed the number and then i incremented :)
i hope it will helpfull
0
Steven Mcilhone
18 April 2019, 20:08
public static void addNewCat() {
//write your code here
Cat cat = new Cat(); //remove this line, everytime you call Cat.addNewCat(); you are creating a object called cat, calling this method again is creating the same object called cat,
catCount++;
}
instead create your objects in the main class
public static void main(String[] args) {
Cat cat = new Cat()
Cat.addNewCat();
Cat cat2 = new Cat()
System.out.println(catCount);
}
0
Vaishnavi
19 April 2019, 15:38
Thank you! I thought I was missing something, but this makes me feel better!
0
somecro
18 April 2019, 18:41
I don't know what your goal is but this is alright.
Everytime you call the addNewCat() method you will create a new Cat object and increment the static catCount variable by one.
0
Vaishnavi
19 April 2019, 15:37
Thanks! This was a big help!
0