Netta
Netta

Reputation: 11

How to make a variable inside a function that saves its value from call to call

I want to know how and if I can define a variable inside a function and accumulate its value in each call. For example:

public int foo(int num, int cost){
     int sum;
     sum += num*cost;
     System.out.println("all costs are "+ sum);
     return sum; 
}

I want the variable sum to accumulate its value from one call to another so that the following calls:

foo(5,3);
foo(2,8);

Will print this output:

all costs are 15
all costs are 31

Can I do this with java? And if yes then how do I do that. I am sorry I don't know the concept I am trying to implements. I know that in other languages it can be done.

Upvotes: 1

Views: 1136

Answers (3)

Zain Arshad
Zain Arshad

Reputation: 1907

What you are doing is creating new object of type int having the same name sumevery time you call the method foo(). As, you are creating new object the previous value will be overwritten.

But you want to save the value for later use. So, to achieve this you have to change the scope of the variable and declare it outside the functions. So, that every method can use it and it can save its previous value.

Working Code:

public class stackInt
{
    public static int sum=0;  // now every method can access this variable
    public static void main(String[] args)
    {
        foo(5,3);
        foo(2,8);
    }

    // according to your output you dont have to set return type as "int"
    public static void foo(int num, int cost)
    {
        sum += num*cost;
        System.out.println("all costs are "+ sum); 
        //return sum; as you have printed the output what you want, so, no need to return "sum"
    }
}

NOTE: In Printing you are using cost but according to output it should be sum, moreover, no need to return sum if you goal is to just print it.

Upvotes: 2

Metin Dagcilar
Metin Dagcilar

Reputation: 554

What you want to do is create a global variable outside of the function that keeps track of the variable.

Like this:

private int sum = 0;

public int foo(int num, int cost){

    sum = sum + num * cost;
    System.out.println("all costs are "+ cost);
    return sum; 
}

If you define int sum; inside the method, each time the method is called it will overwrite the variable which is not what you want in your case.

Upvotes: 0

jonathan Heindl
jonathan Heindl

Reputation: 851

in java you can add variables on classes so it would look something like this:

int sum=0;

public int foo(int num, int cost){

 sum += num*cost;
 System.out.println("all costs are "+ cost);
 return sum; 
}

the variable will then only be reset for every instance you make of the class the foo method is on

if you want to persist it across different instances as well you can do

static int sum=0;

instead

Upvotes: 0

Related Questions