how avoid set a global variable in recursive class - java

I have a global variable in a recursive class, each time I call it, the variables are created. The variable at begin is: int count = 0, then in the method I increase: count ++, the problem is when call again the class, the variable is reset to zero. I need the variable "count" remains in 1, to again increase in each call to 2,3,4.... etc
I try with this: private static int count = 0; but not work..

Search the code for all references to your count variable. Most likely, you are re-setting to 0 somehow. For example:
private class MyClass {
private static int count = 0;
public MyClass() {
count = 0; //Bad line
}
public void incrementCount() {
count++;
}
}
If you have something like that, then every time you create a new MyClass object, you would be resetting count to 0 for all MyClass objects.
But you really need to add your class code to your question. Otherwise we can't help.

Related

writing a static method to set counter java?

I am pretty new to coding, I want to write a static method to set a count value to 1000.
I tried doing things like
public static int setCounter(){
return 1000;
}
When try to use this method in another to increment the count
such as someVariable = symbolic constant + setCounter()++;
return someVariable, it gives me an unexpected type error, required variable, found value. What am i doing wrong?
edit*
edit*
private String getTicketNumber(){
ticketNumber = TICKET_PREFIX + resetCounter()++;
return ticketNumber;
public static int resetCounter(int counter){
counter = 1000;
}
i want to call this counter to increment it in another method
An static property is associated with the definition of the class, and there is only ever one definition of the class. An instance is created whenever you use the new keyword on the class. All instances are keep their own private data from the static class. When using a class instance you can access the static variables but not the other way around.
You use the term constant, but I think you might have a bit of a misunderstanding of what that implies. Constants are often declared as static final values that are immutable (they can never be changed). You should not be able to modify a constant. A static value can be mutable if you so desire, and this is what we would sometimes refer to as a stateful singleton.
Consider these two examples... one modifies an instance variable, the other a static variable.
class InstanceFoo {
int i = 1000;
int resetCounter() {
i = 1000;
return i;
}
int getAndIncrement() {
return i++;
}
}
class StaticFoo {
static int i = 1000;
static int resetCounter() {
i = 1000;
return i;
}
static int getAndIncrement() {
return i++;
}
}
In the first example you need to use an instance to access the variables.. i.e. you need to instantiate it with new:
InstanceFoo foo = new InstanceFoo();
System.out.println(foo.resetCounter()); // 1000
System.out.println(foo.getAndIncrement()); // 1000
System.out.println(foo.getAndIncrement()); // 1001
System.out.println(foo.getAndIncrement()); // 1002
System.out.println(foo.resetCounter()); // 1000
In the second you access the static value. Statics can be referred to by to the class definition:
System.out.println(StaticFoo.resetCounter()); // 1000
System.out.println(StaticFoo.getAndIncrement()); // 1000
System.out.println(StaticFoo.getAndIncrement()); // 1001
System.out.println(StaticFoo.getAndIncrement()); // 1002
System.out.println(StaticFoo.resetCounter()); // 1000
In your example you are trying to increment the counter by doing resetCounter()++. This will not work for a separate reason entirely from being static or instance. Primitive values in Java (like ints, doubles, floats, etc) are pass by value, not pass by reference.
In a very simplistic sense, this means that once you return a primitive from a method like resetCounter, you are actually passing a copy of the value. You then incremented the copy, but the value associated with the class remains the same (because you incremented only the copy of the variable). You need to call the postfix operator ++ on the variable itself, not the value returned by the method. i.e. If I have
class StaticFoo {
static int i = 1000;
static int get() {
return i;
}
}
System.out.println(StaticFoo.get()++); // prints 1000 and adds 1. the copy is then destroyed
System.out.println(StaticFoo.get()++); // prints 1000 and adds 1, the copy is then destroyed
System.out.println(StaticFoo.i); // prints 1000
System.out.println(StaticFoo.i++); // prints 1000 and now a postfix is applied to the static variable
System.out.println(StaticFoo.i++); // prints 1001 and another postfix is applied to the static variable
System.out.println(StaticFoo.get()); // prints 1002 because two postifx operators were applied to StaticFoo.i.
Hope this helps you get started.
I think that you are assigning value to a non compatible data type varaiable.
See my code for reference:
public class Main
{
public static void main(String[] args) {
System.out.println("Hello World");
int a = 10 + setCounter();
System.out.println(a);
}
public static int setCounter(){
return 1000;
}
}
edit*
private String getTicketNumber(){
ticketNumber = TICKET_PREFIX + resetCounter()++;
return ticketNumber;
public static void resetCounter(int counter){
counter = 1000;
}
i want to call this counter to increment it in another method

how does this code give new id for each thing object. id should be equal to 1 all the time

class Thing {
public static int count = 0;
public int id = 0;
public Thing() {
id = count;
count++;
}
public void ID() {
System.out.println("This object has id: " + id);
}
}
public class wth {
public static void main(String[] args) {
Thing thing1 = new Thing();
Thing thing2 = new Thing();
Thing thing3 = new Thing();
thing1.ID();
thing2.ID();
thing3.ID();
}
}
Shouldn't this code print 1
1
Here is what I understand of the code:
First of all, the thing1 object is created and the constructor Thing runs thus making id=0 and count=1. Then thing2 is created and again the constructor runs making id=1 and count=2.
Now thing1.ID() runs printing the value of id which should be 1 but instead its 0 please explain how is it 0.
public static int count=0;
This line means that the variable count is linked to the class, not the object. So every time a new Thing is created, the incrementation of this variable is applied across all the objects instantiating the class, including new instances that are made.
You can find more info in the official doc/tutorial here.
This code illustrates the way static works. count is shared among all objects of the class, so it gets incremented each time a new Thing object is instantiated.
Note: This will break in concurrent environments: if you run this from multiple threads, some objects may get the same id. A better implementation would use AtomicInteger:
class Thing{
public static AtomicInteger count = new AtomicInteger(0);
public int id;
public Thing(){
id=count.incrementAndGet();
}
...
}
count is static, which is why it gets incremented each time you create a new instance of Thing but id isn't. That means that each instance of Thing, being thing1and thing2 will each have their own id.
In your question:
value of id which should be 1 but instead its 0 please explain how is
it 0.
What I understood, you asking for first time you create object it's value should be 1 and next time increment by 1. If it is asked for,
Reason:
When you create first object(thing1) you are calling default constructor(Thing()), which you have implemented. And in the first line you assigning count variable value to id variable which is 0. Then you increment count by one. It is not affecting to id variable first time. Then, you call the ID() method, it will print, value that it hold 0.
Solution:
public Thing() {
id = count;
count++;
}
move the count++; to first line. Should be:
public Thing() {
count++;
id = count;
}
Output become:
This object has id: 1
This object has id: 2
This object has id: 3
Because of static each time you create new object count will increment.
If you want to get outputt as 1 every time:
First you want to know about static keyword:
Attributes and methods(member of a class) can be defined as static.
static members do not belongs to an individual object.
static members are common to all the instances(objects of the same class).
static members are stores in static memory(a common memory location which can by everybody).
The static modifier indicates that the count variable(attribute) are common to all the Thing in the whole class rather than to an individual object.
To answer your question:
public static int count = 0;
As I mention above this count variable common for all the objects. That means when you create a different objects it's value not changed.
remove the static modifier, should be:
public int count = 0;
When you removed static modifier count variable become individual for all the objects that you are creating. And for each object it will print as follows:
This object has id: 0
This object has id: 0
This object has id: 0
If you move the count++; to first line.
public Thing() {
count++;
id = count;
}
Output become:
This object has id: 1
This object has id: 1
This object has id: 1

Can instance variable be declared as static variable in java

I wrote the following code:
public class Count
{
private static int[] array;
public Count( int[] array )
{
this.array = array;
}
public int count()
{
int count = 0;
for (int i = 0; i < array.length; i++) {
int x = array[i];
if (x < 0) {
if (x == -1 && i > 0 && array[i - 1] == -1) {
break;
}
} else {
count++;
}
}
return count;
}
}
and then in another class I wrote:
Count c = new Count(new int[]{1,-1,-1});
and checked the result of c.count().
I didn't get a compiler error,and I got 1 as I wanted.
I wonder why because how can I assign a static variable to an instance variable?
And also, what happens if I create another instance of class Count?
Will they both have the same variable?or just their own copy of it? and what should happen if I try to access the variable by writing Count.array?
Thanks.
array is shared between all the instances of Count - they can all read from it and write to it. And as you stated, if you instance modifies it, all the other instances will see the newly modified value.
Classes can access their own static members.
All classes will see the same static members (ignoring thread contention complications).
If you create another instance of Count they will both be modifying the same variable.
That's what static means...
I'd recommend that you write the example you're asking about and see. There's no better authority than the JVM, and it'll tell you faster than SO will.
I think you should understand the meaning of class and instance variables and pick the one that matches your intent.
So it's either class:
public class Count
{
// Shared by all
private static int[] array;
}
or instance:
public class Count
{
// Owned by instance
private int[] array;
public Count(int [] v) {
if (v == null) throw new IllegalArgumentException("array cannot be null");
this.array = new int(v.length);
System.arraycopy(v, this.array, 0, v.length);
}
}
You should not just assign the array reference to the private data member. You need to allocate memory and copy the values into it. Otherwise the supplier of the input array will modify the private values if it updates using their reference.
Too many people don't realize that assigning mutable references to private members breaks encapsulation. Maybe you won't be one of them now.

What is non-final variable?

I am not understanding the concept of final variable. In a for loop I have dynamic variable i which is crucial for me to refer an array. As soon as I use i, it throws me an error saying it should be final.
What exactly is final? Could you please help to get rid of that error?
My code is here:
for( int i = 0; i <4; i++)
{
Bitmap celeb1=Bitmap.getBitmapResource(fimagearray[i]);
Bitmap celeb1_focus=Bitmap.getBitmapResource(fimagearray[i]);
ImageButton celebbutton = new ImageButton(celeb1, celeb1_focus);
celebbutton.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context)
{
UiApplication.getUiApplication().pushScreen(new FetchTweets(fusernamearray[i]));
}
});
femaleSec.add(celebbutton);
}
An anonymous inner class can only access final variables from the outer scope. Since i is not final, it can't be accessed directly. You can't make i final since it needs to change, and a final variable can't be changed.
As a simple workaround, copy the value of i into a final variable during each loop iteration:
for( int i = 0; i < 4; i++)
{
final int index = i; // <-- copy i to `index' to use in FieldChangeListener
// ...
celebbutton.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context)
{
UiApplication.getUiApplication().pushScreen(
new FetchTweets(fusernamearray[index])); // <-- `index'
}
});
femaleSec.add(celebbutton);
}
A final variable can only be initialized once, either via an initializer or an assignment statement
Check out the this link for it.
Also Look at this Example.
You are attempting to use the value of i inside of an 'Anonymous Inner Class' which requires that all non-local variables to that class be declared as final, meaning that the variable's value may not be changed once it has been initialized.
The solution posted by #aix would solve your problem.

Counter that will remember its value

I have a task to operate on complex number. Each number consists of double r = real part, double i = imaginary part and String name. Name must be set within constructor, so I've created int counter, then I'm sending its value to setNextName function and get name letter back. Unfortunately incrementing this 'counter' value works only within costructor and then it is once again set to 0. How to deal with that?Some constant value? And second problem is that I also need to provide setNextNames(char c) function that will change the counter current value.
The code :
public class Imaginary {
private double re;
private double im;
private String real;
private String imaginary;
private String name;
private int counter=0;
public Imaginary(double r, double u){
re = r;
im = u;
name = this.setNextName(counter);
counter++;
}
public static String setNextName(int c){
String nameTab[] = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N",
"O","P","Q","R","S","T","U","W","V","X","Y","Z"};
String setName = nameTab[c];
System.out.println("c: "+c);
return setName;
}
public static String setNextName(char c){
//
//don't know how to deal with this part
//
}
It's hard to tell what you're doing, but I suspect this will solve your immediate problem:
private static int counter = 0;
You should make counter static.
You should also make nameTab a private static field, then in setNextName(), you can iterate through it to find the name corresponding to the given character, and get its index. (in the plain ASCII world, of course one could simply calculate the index by subtracting the numeric value of 'A' from the given character, but I am not quite sure how it would work out with Java, in Unicode, with crazy inputs - iteration is on the safe side.)
In OO languages there are typically two types of variables that go into a class:
instance variables that are unique to each instance
class variables that are shared by all instances of the class
Given a class like:
public class Person
{
// class variable
private static int numberOfEyes;
// instance variable
private String name;
// other code goes here
}
If you were to do something like:
Person a = new Person("Jane Doe");
Person b = new Person("John Doe");
and then do something like:
a.setName("Jane Foe");
the name for Person "a" would change, but the one for Person "b" would stay the same.
If you woke up one morning and decided you wanted 3 eyes:
Person.setNumberOfEyes(3);
then Person "a" and Person "b" and every other Person instance out there would suddenly have 3 eyes as well.
You want to put "static" in your counter declaration.
is your code being used by multiple threads than i would suggest that making counter static won't solve ur problem.
you need to take extra care by implementing thread synchronization use lock keyword as shown below.
private static readonly obj = new Object();
private static int counter =0;
public Imaginary(double r, double u)
{
re = r;
im = u;
lock(obj)
{
name = this.setNextName(counter);
counter++;
}
}
this will ensure thread safety also while incrementing your counter (there are another ways also to provide thread security but this one is having least code).
Because the field counter is not static, every object has its own counter.

Categories