user2875021
user2875021

Reputation: 135

java count the times String argument is stored in a Object

for the method public int count(String str)
How can I return the number of times that String argument str is stored in an Object?

I have written the following code but I think it is not suppose to do this.

public int count(String str)
{
  int count = 0;
  // if the Object contains str
  if(contains(str)) {
    count++;
  else {
    add(str); //add str to Object
    count++;
  }
  return count;
}

When I typed in command line, eg "test" the count is 1. but when i typed "test" again, the count remains 1. (it should suppose be 2).

Thank you in advance.

Upvotes: 0

Views: 56

Answers (3)

Varun Moghe
Varun Moghe

Reputation: 124

You should declare it as a global variable. The statement int count = 0; resets the variable value to 0. Hence when again tested it updates from 1 to 0 and again to 0.That should be the problem.

Upvotes: 1

azurefrog
azurefrog

Reputation: 10945

Your method can never return anything but 1, since you initialize count = 0 each time you run it.

Make count a class variable instead of a local variable, so that it will maintain its value between invocations of the method.

Upvotes: 1

PSR
PSR

Reputation: 40318

Then declare the count variable as global.

Upvotes: 1

Related Questions