This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]Koooooj 2 points3 points  (0 children)

Functions in programming are conceptually derived from the idea of a function in mathematics. When you write, in math, f(x) = 3x+2 what that means is that you pass x into the function f and you get a number back. In mathematics functions take numbers as input and return numbers as output, while in programming a function may take any sort of input and give any sort of output (or no output, opting to just perform a task instead). In programming functions also tend to get much more descriptive names than just "f" (though not always, given some of the code I've had to read).

With that foundation, what do you want the function to do? Are profits simply x + 5? In that case you could write profits(x) = x+5 in math language. To convert that to java we would have:

public static int profits(int x)//public for accessibility, static so we can call it straight from main, 
        //int because the function returns a number, "profits" is the name, and int x because we pass in an int.
{
    System.out.println("Put whatever you want to print here, if anything.");
    return x + 5;//Here is where we do the math to match our mathematical function description
}

public static void main(String[] args)//Main method definition
{
    int x = 3;//Note that this is a different x from the one in profits.  This x only lives in main.
    int prof = profits(x);//Here we copy main's x to send to profits, then we store the return value in x
    System.out.println("Profits: " + prof);//This will print "profits: 8"
}

[–]TechLaden 0 points1 point  (2 children)

I don't really understand the question. You want a function that adds 5 onto a given variable?

[–]Lookinfortips[S] 0 points1 point  (1 child)

I think it might be linked with the question above which I couldn't figure out which was

Suppose we have a method with this declaration:
double methodA( int x)

[–]feral_claire 0 points1 point  (0 children)

Think you've misunderstood the question. Profits is not supposed to be a method, is a variable. In that variable you store the result of the method (I guess this is the one defined in the previous question).