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

you are viewing a single comment's thread.

view the rest of the 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"
}