ReverseArray Method
From CompSciWiki
Back to the Program-A-Day homepage
ProblemLet's now expand on the printArray program with an additional twist. Recall you created a method to print the names of students stored in different arrays for different classes. You have now discovered that it would be useful to be able to print the names of the students in reverse order, and must add a method to the program to do this. Take the sample solution from printArray below and add a reverseArray method to it. This method should accept an array of Strings as input and return a reversed version of this String array as output. =public class PrintArray{ public static void main (String [] args){ String [] comp1010 = { "Adam", "Bob", "Carl", "David", "Edward"}; //class list for comp 1010 String [] comp1020 = { "Amy", "Beth", "Cindy", "Dawn", "Ellen"}; //class list for comp 1020 String [] comp1260 = { "Mike", "Mary", "Matthew", "Megan", "Moe"}; //class list for comp 1260 System.out.println("COMP 1010:"); printArray(comp1010); //note that since the method is void, you just use the name of the method System.out.println("COMP 1020:"); //followed by the name of the array in brackets printArray(comp1020); System.out.println("COMP 1260:"); printArray(comp1260); System.out.println("--End of Processing--"); } public static void printArray(String [] courseList){ //note that the method is void, and the input variable is an array of Strings //We called the array "courseList", since this can refer to any of the arrays //we send it for (int i=0; i<courseList.length;i++){ //for loop to go through each element in the array System.out.println(courseList[i]); //print the current element } System.out.println(); //add a blank line after the list of students } } |
SideSectionTitle
An image or By Students section | |
---|---|---|
SolutionStuff about the Solution | ||
Code |