133k views
2 votes
Create a method called nicknames that passes an array as a parameter. Inside the method initialize it to hold 5 names of your choice. Use the for each enhanced loop to print the elements of the array.

User SteveFerg
by
5.0k points

1 Answer

6 votes

Answer:

//======METHOD DECLARATION=========//

//method name: nicknames

//method return type: void

//method parameter: an array reference

public static void nicknames(String [] names){

//initialize the array with 5 random names

names = new String[] {"John", "Doe", "Brian", "Loveth", "Chris"};

//using an enhanced for loop, print out the elements in the array

for(String n: names){

System.out.print(n + " ");

}

}

Step-by-step explanation:

The program is written in Java. It contains comments explaining important parts of the code. Kindly go through these comments.

A few things to note.

i. Since the method does not return any value, its return type is void

ii. The method is made public so that it can be accessible anywhere in and out of the class the uses it.

iii. The method is made static since it will most probably be called in the static main method (at least for testing in this case)

iv. The method receives an array of type String as parameter since the names to be stored are of type String.

v. The format of initializing an array manually should follow as shown on line 7. The new keyword followed by the array type (String), followed by the square brackets ([]) are all important.

vi. An enhanced for loop (lines 9 - 11) is a shorthand way of writing a for loop. The format is as follows;

=> The keyword for

=> followed by an opening parenthesis

=> followed by the type of each of the elements in the array. Type String in this case.

=> followed by a variable name. This holds an element per cycle of the loop.

=> followed by a column

=> followed by the array

=> followed by the closing parenthesis.

=> followed by a pair of curly parentheses serving as a block containing the code to be executed in every cycle of the loop. In this case, the array elements, each held in turn by variable n, will be printed followed by a space.

A complete code and sample output for testing purposes are shown as follows:

==================================================

public class Tester{

//The main method

public static void main(String []args){

String [] names = new String[5];

nicknames(names);

}

//The nicknames method

public static void nicknames(String [] names){

names = new String[] {"John", "Doe", "Brian", "Loveth", "Chris"};

for(String n: names){

System.out.print(n + " ");

}

}

}

==================================================

Output:

John Doe Brian Loveth Chris

NB: To run this program, copy the complete code, paste in an IDE or editor and save as Tester.java

User JasonStoltz
by
5.2k points