<< Back Computer Science Club

November 20 2019 - Challenge 1 (addition addiction!), Java 6 (methods 2)

At this meeting, we did the first challenge and some more stuff with methods.

I'm doing the meeting logs for both 11/13 and 11/20 at the same time (along with like 3 other ones lol I'm so behind), so we may have done the stuff in the two logs in a different order.




Addition Addiction! - Challenge 1

Use your knowledge of arrays, user input, loops (optional), and other stuff to take 5 numbers from the user and print out their sum.

Go to challenge




Intro to Methods and Arguments

If you check out last week's meeting log, you'll get a basic overview of writing and calling methods.

Now, let's make them a bit more useful.


Method arguments
If you look at the method you write, you might be curious as to why there are those empty () at the end of the method name. Are they just there to indicate that it's a method? No, there's something else.

Introducing: method arguments. Let me show you some example code, then we'll explain it below.

public int combineNumber(int numberOne, int numberTwo, boolean add) {

 int newNumber = 0;

 if (add) {
  newNumber = numberOne + numberTwo;
 } else {
  newNumber = numberOne - numberTwo;
 }

 return newNumber;

}


Okay, so there's a lot going on in that code (actually no there isn't, it's really basic). Here's what's happening:

The method is asking for three arguments: two numbers and a boolean. It's like creating variables without setting their values (because that's done later).

If add is true, it'll take the two numbers, add them, and then return them.
If add is false, it'll take the two numbers, subtract them, and then return them.


Now, let's use this method with some numbers:

public void run() {

 int first = combineNumber(5, 82, true);

 int second = combineNumber(471, 928, false);

 int numberOne = 1;
 int numberTwo = 10000;
 boolean shouldIAdd = true;

 int third = combineNumber(numberOne, numberTwo, shouldIAdd);

}


To use arguments, simply put their values in the same order as you ask for them between the two parentheses.

Figure out what the ints first, second, and third should be equal to, then look below.



first is equal to 87, second is equal to -457, and third is equal to 10001.


Remember, you can put any variable type or object as method arguments, not just ints and booleans.




If you have any questions, ask them at Computer Science Club!