Less code, more function
Let's start with this code:
System.out.println("You have 8 apples. The cost is $8.");
Then add this on:
System.out.println("You have 7 avocados. The cost is $14.");
These prints are generally the same except for:
- The item bought
- The amount of said item
- The cost of the total items
If we want to create a Receipt in Java, we will end up with tons of println()s, and potentially more lines of variables for the calculations for price.
It will get very messy and tedious quickly. Luckily, we can use methods to fix this problem:
void Methods
We will be working with void methods in this lesson and return methods in the next lesson.
A method is essentially a group of code we can enter new information into(or not) and repeat it every time we call it.
Below your main method (but still before your Main class), write this code:
public static void groceryItem(String item, int amount, double cost) {
double total = cost * (double)amount;
System.out.println("You have "+ amount +" " + item + ". The cost is $"+total+".");
}
We have already created a method earlier, but we will learn more about the specifics here.
Let's break this down the line by line:
In the first line, we write public (we will learn more about this), which allows it to be accessible in other classes if needed.
By writing static, we can use it/call it without the overall Main class being initialized.
The void is the big thing: It basically means it doesn't return anything. When methods return values, we can use them like variables or the values of variables. (More in the next lesson)
We then give the method a name; In this case, we called it groceryItem. These names need to be unique and follow the same rules as naming variables.
Parameters
Now you should see the values in the parenthesis: these are called parameters.
They are local variables to the method representing the values we will input when we call the function.
We specify the data type and give the parameter a name. You can use it just like you would a normal variable.
Calling the method
Now, let's see this method in action; In your main method (see?), write the following:
public static void main(String[] args) {
groceryItem("apples",8,1);
groceryItem("avocados",7,1.5);
groceryItem("oranges",5,2);
Notice how the data types match perfectly to what we wrote in our parameter list? If we don't make sure they match up, we will have a few bugs.
Hit run, and you should see the following printed:
You have 8 apples. The cost is $8.0.
You have 7 avocados. The cost is $10.5.
You have 5 oranges. The cost is $10.0.
Yes, the decimals are still weird, but everything else looks good.
And that's how methods work! Try experimenting and playing around with them, and see what you can do.