Thursday, March 31, 2016

Use Methods with Parameters

Hey guys, welcome to another java tutorial. In this post we're gonna talk about Parameters and use them with Methods.


I think you've read last post & understood the Multiple Classes very well. So the next step.. follow up..

As we did before our main class(main.java) & our sub class(sub_clz.java). OK

  • First of all clear all the coding in the main class & sub_clz.
  • In the sub_clz write the following code.

public class sub_clz {
public void simpleMSG(String name){

System.out.println("Hello " + name);

}

}

  • You can see a little bit of change with previous post. Last time we put public void simpleMSG() ] like this.
  • But this this we put String name ] variable into the brackets. This is what we call Parameters
  • Don't get panic.... go to next code System.out.println("Hello " + name); ]
  • We tell the computer to display " Hello " and a name (parameter).
  • OK. Now go to the main class and import a scanner. (Scanners)
  • Then in the main method create a scanner object & assign the value to the a String. ( I named it input ).
  • As we did last time create class object.
  • And call sub_clz.
I know y'all freaked out. See the code

import java.util.Scanner;       // importing a scanner
public class main {

public static void main(String[] args){

   Scanner in = new Scanner(System.in);     //  creating the scanner object
  System.out.println("Enter your name ?");      
  String input = in.nextLine();

sub_clz sub = new sub_clz();       // creating sub_clz object
sub.simpleMSG(input);           // assigning the value to name in sub_clz

}
}

Recap : In the sub_clz, we created a method called [ public void simpleMSG(String name) ] which has a parameter.
Next in the main class imported a scanner & ask user to input the name. The name was assigned to String variable called  [ input ].
Then we called [ simpleMSG ] method in sub_clz & assiggn the value of [ input ] to [ name ].



 

No comments:

Post a Comment