PDA

View Full Version : Java Methods


ihateaol
01-14-2007, 06:25 PM
Hey Everyone,

Does anyone know a website that explains how java methods work in a detailed, and easy to understand way for a beginner? I have a JAVA final exam on thursday and the one thing that's on it that I don't get are methods. I mean, I know what they are and why they're there, but I don't know how they work. I always get confused on what to put in the braces after "public static void(int/double) methodName (what do I put here?)" I mean, I know I put variables there, but which one's? One's that I use throughout the entire program? Or one's I'm just using in that method? And if it's just the one's I'm using in that method, how does that method read the one's that are used throughout the program? And returning stuff also baffles me. How does it know where to return to? I know you tell it where, but how? Basically, as you can see, I'm totally lost on how to convert a normal program into a program that uses methods.

This is the program I'm currently trying to convert: It allows the user to input as many numbers as he or she wants, then sorts them by negatives, evens, and odds. As you can see, I can make the actual program, I just can't put it into methods!

import java.util.Scanner;

public class ArrayProgram2{

public static void main(String [] args){

//Variables
Scanner reader = new Scanner(System.in);

int howManyNums;
int counter, j = 0, k = 0, h = 0;
int numOfEvens = 0, numOfOdds = 0, numOfNegs = 0;

System.out.print("How Many Numbers?: ");
howManyNums = reader.nextInt();
int[] list = new int[howManyNums];
System.out.println();

for(counter = 0; counter < howManyNums; counter++){
System.out.print("Number " + (counter + 1) + ": ");
list[counter] = reader.nextInt();
if ((list[counter] % 2 == 0) && (list[counter] > 0)){
numOfEvens++;
}
if ((list[counter] % 2 != 0) && (list[counter] > 0)){
numOfOdds++;
}
if (list[counter] * 2 < 0){
numOfNegs++;
}
}

int[] listOfEvens = new int[numOfEvens];
int[] listOfOdds = new int[numOfOdds];
int[] listOfNegs = new int[numOfNegs];

for(counter = 0; counter < howManyNums; counter++){
if ((list[counter] % 2 == 0) && (list[counter] > 0)){
listOfEvens[j] = list[counter];
j++;
}
if ((list[counter] % 2 != 0) && (list[counter] > 0)){
listOfOdds[k] = list[counter];
k++;
}
if (list[counter] * 2 < 0){
listOfNegs[h] = list[counter];
h++;
}
}
System.out.println();
System.out.println();
System.out.println("Results: ");
System.out.println();
System.out.println("Entire List: ");
for (counter = 0; counter < howManyNums; counter++){
System.out.println("Number " + (counter + 1) + ": " + list[counter]);
}
System.out.println();
System.out.println("Evens: ");
for (counter = 0; counter < numOfEvens; counter++){
System.out.println("Number " + (counter + 1) + ": " + listOfEvens[counter]);
}
System.out.println();
System.out.println("Odds: ");
for (counter = 0; counter < numOfOdds; counter++){
System.out.println("Number " + (counter + 1) + ": " + listOfOdds[counter]);
}
System.out.println();
System.out.println("Negatives: ");
for (counter = 0; counter < numOfNegs; counter++){
System.out.println("Number " + (counter + 1) + ": " + listOfNegs[counter]);
}

}
}

Any help at all would be good. A self explanation, or a web link would be amazing. (Also, sorry about the unneeded tab over after the variables).

brad211987
01-14-2007, 09:24 PM
I'll give you a quick example to try and answer a few of your questions.

Suppose we have a method that looks like this:


public int getSum(int x, int y)
{
int z = x + y;
return z;
}


Now we can look at the method part by part. This method is "public" meaning that any class can use this method if it creates an instance of the class containing this method. Next we have the return type, in this case, this method will return an int value. Then of course is the method name and its two parameters. The parameters are 2 ints, meaning that this method will accept 2 integer values as parameters, and use them with the names x, and y within the method body. Inside the method, it assigns the value of x + y to variable z, and then returns that value.

Lets look at how the method is used now, with the above method, we could have the code:

int num1 = 5;
int num2 = 6;
int sum = getSum(num1,num2);


In the above code, we define 2 integer variables and pass them into the getSum method, and we store the value returned in variable sum. The important thing to remember, is when you use num1, and num2 to pass into the method, you pass a copy of those variables, and the method assigns that value to its own variables(x and y). After the method is done executing and returns its value, the variables used within the method (x, y and z) do not exist anymore, and all you are left with is the variables num1, num2, and sum, which contains the sum of num1 and num2.

If you have any more questions, feel free to ask and I can try to clarify further. Also if you google for "java tutorials" you should find many resources that will most likely have a wealth of information about methods and classes.

daniel_g
01-14-2007, 11:12 PM
Keeping in mind what brad said, here's how you would turn a main method into multiple methods:

public class SomeClass{
public static void main(String[] args){
int a = 1;
int b = 2;
int c = 3;
int d = 4;
int ab, cd, result;

ab = a+b;
cd = c+d;
result = ab + cd;
System.out.println(result);
}//end main
}//end class

you could change it into:

public class MyClass{

public int method1(int a, int b){
int ab = a+b;
return ab;
}//end method1

public int method2(int c, int d){
int cd = c+d;
return cd;
}//end method2

public static void main(String[] args){
int result = method1(1,2) + method2(3,4);
System.out.println(result);
}//end main

}//end class


Note that local variables of one method do not intefere with local variables of another method. For example, the sample code I gave you can be writen as:

public class MyClass{

/*
* Note method1 and method2 use the same variable names, but it
* doesn't matter since the main method assigns them different values
*/

public int method1(int a, int b){
int ab = a+b;
return ab;
}//end method1

public int method2(int a, int b){
int ab = a+b;
return ab;
}//end method2

public static void main(String[] args){
int result = method1(1,2) + method2(3,4);
System.out.println(result);
}//end main

}//end class


Also note that a method can take as many parametes as you need, or no parameters at all. It all depends on your needs. For example you could have a method like this:

method(var1, var2, var3, etc){
//some code
}
or just something like this:

method(){
//some code
}

ihateaol
01-15-2007, 01:30 AM
Thanks so much to both of you for the help! It's really appreciated.

However, I'm still a little confused on somethings. Like this part:

int result = method1(1,2) + method2(3,4);

You returned ab, and cd in an earlier method, but never used them. Did you returning them just make the method work? Also, where'd you get the 1,2 and 3,4 from???

Gox
01-15-2007, 02:26 AM
Thanks so much to both of you for the help! It's really appreciated.

However, I'm still a little confused on somethings. Like this part:

int result = method1(1,2) + method2(3,4);

You returned ab, and cd in an earlier method, but never used them. Did you returning them just make the method work? Also, where'd you get the 1,2 and 3,4 from???
I think you may be a little confused on how a program is executed. The fact that you said "You returned ab, and cd in an earlier method, but never used them", leads me to believe you're trying to read the code linearly as an execution path. This is not the case. Refer to daniel_g's code and I'll try to clear some things up.

When your program runs, it starts by executing what's in the "main" method. Whether your main method is at the bottom of your code file or the top makes no difference, the program will always start by executing "main". So daniel_g's code will start by executing main, and method1 and method2 are only executed when they are "called" by the main method.
i.e. int result = method1(1,2) + method2(3,4); Callss method1 and method2 to execute.

Since method1 and method2 take integers as parameters, he passed the numbers 1,2 and 3,4 as parameters as they are of course integers. The parameters don't have to be variables, they can be "raw" numbers.

When the program runs it will see method1(1,2) and replace it by what method1 returns. It will then do the same when the program gets to the method2(3,4) method call. You can think of the resulting line of code as followings...When the program executes
int result = method1(1,2) + method2(3,4);
WILL BE REPLACED BY
int result = 3 + 7;
3 is what is returned by method1(1,2) and 7 is what is returned by method2(3,4).

One reason to have a method is to put a "wrapper" around some section of code that we might use more than once. That way we don't have to retype a section of code multiple times, we can just call the method to execute various times within out main program.

public class MyClass{

public static void main(String[] args){
System.out.println("This is some large amount of text");
System.out.println("Maybe the instructions on how to use");
System.out.println("My program that I wish to display everytime");
System.out.println("The program starts or");
System.out.println("The user hits the 'h' key");

if(user hits h key)
{
System.out.println("This is some large amount of text");
System.out.println("Maybe the instructions on how to use");
System.out.println("My program that I wish to display everytime");
System.out.println("The program starts or");
System.out.println("The user hits the 'h' key");
}
}//end main

}//end class

The point of the above code is to illustrate that if we have a large number of lines of code that we might use more than once, (in this case displaying the help file when the user hits h) and we don't have it in a method, then we have to retype it in the code everytime. You'll notice that in the above code I had to type all the System.out's twice. But what if we made a method for the duplicated code.....

public class MyClass{

public static void main(String[] args){
printHelpFile();

if(user hits h key)
{
printHelpFile();
}
}//end main

public void printHelpFile()
{
System.out.println("This is some large amount of text");
System.out.println("Maybe the instructions on how to use");
System.out.println("My program that I wish to display everytime");
System.out.println("The program starts or");
System.out.println("The user hits the 'h' key");
}

}//end class

Now that the helpfile contents are in a method, everytime I want to display these contents all I have to do is call printHelpFile() from the main method. This way I don't have to retype all that code everytime.