AkshaiShah
AkshaiShah

Reputation: 5939

Getting value to increment and return after each incrementation

I am trying to increment a variable from 0-99, and return the value each time, but I'm unsure how i could do this. This is the code i have so far:

public int getValue()
{
  if (currentState == COUNTING)
  {
    for (int i = 0; i <= 99; i++)
    {
      value = i;
    }

    return value;      

  } else {
    return super.getValue();   
  }
} 

I'm not sure how I could modify this, as at the moment it is returning 99. I know why, but do not know how to accomplish what i am trying to do.

Upvotes: 1

Views: 3683

Answers (5)

Korhan Ozturk
Korhan Ozturk

Reputation: 11308

Unfortunately, strictly speaking you cannot return multiple values from a method call. A method in Java can only return a single primitive value or Object..

Your code returns 99 because the final 'value' of your loop variable 'i' is 99 when for loop finishes to execute. Instead you should try returning your values hold in an Integer Array.

Upvotes: 4

Mike Bockus
Mike Bockus

Reputation: 2079

Have a class variable that maintains the value, then return the incremented value each time getValue() is called

private int value=0;
public int getValue()
{
  if (currentState == COUNTING)
  { 
    return value++;
  }
  else
    return super.getValue();   
} 

Upvotes: 0

Alexander Corwin
Alexander Corwin

Reputation: 1157

In java a function can only return once; at that point it exits the function. You might be interested in this question.

So the short answer is no. If you can give more context as to what you're trying to accomplish, it might be possible to try to help explain a good way to do it in Java.

Upvotes: 1

Dan Kanze
Dan Kanze

Reputation: 18595

If you need to preserve formatting, for each number on its own line, then you will need to append a new line \n or endl.

If you are trying to simply print 1-99 using a single method and a single return, you will need to use an array.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258578

You can create a static member and increment it on each call.

class MyClass
{
   private static int value = 0;
   public int getValue
   {
       if ( value >= 99 )
          return value; //or throw exception, whatever
       else
          return value++;
   }
}

EDIT: If your getValue is bound to an instance of the class, there's no need to make value a static. If you want each call on the method to return an increment value, regardless of the object it's called on, you have to make it static.

Upvotes: 0

Related Questions