java method parameters
You can pass values to your methods so that something can be done with this value. That value goes between the round brackets of the method.Switch back to your MyMethods class. Now add the second of our total methods:
int total( int aNumber ) {
int a_Value = aNumber + 20;
return a_Value;
}
int total( int aNumber ) {
int a_Value = aNumber + 50;
return a_Value;
}
Although the two methods do different things, they have the same method headers.
Before you try out your new method, add some comments directly above the method:
All we're doing with the method itself is passing it an integer value and adding 20 to this passed value. The return value is the total of the two.
Now switch back to your code and add the following line:
int aVal2 = test1.total(30);
As soon as you type the dot after your test1 object, you'll see the
popup list again. Your new total method will be on it. Click on the new method
to highlight it and NetBeans will display the following:But once you have added the total2 method, type the number 30 between the round brackets. Then type a semi-colon to end the line. You main method should now look like this:
Add a print line to your code:
System.out.println( "Method result2= " + aVal2
);
Then run your programme. The Output window should display the following:In the next lesson, you'll learn how to pass more than one value over to your methods.
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment