Difference between revisions of "ReverseArray Method"
(edit: in reverseArray the variable i is the index for reversed, undated the lenght check in the loop to match) |
m (Removed <pre> tags from SolutionCode.) |
||
Line 42: | Line 42: | ||
|Solution=To make your reverseArray method work, use a for loop to cycle through a second array from start to finish, and use a seperate int, decrimented each loop, to cycle through the original array from end to start. In each iteration of the loop, copy the entry from the old array to the new one, and return the new array. | |Solution=To make your reverseArray method work, use a for loop to cycle through a second array from start to finish, and use a seperate int, decrimented each loop, to cycle through the original array from end to start. In each iteration of the loop, copy the entry from the old array to the new one, and return the new array. | ||
− | |SolutionCode= | + | |SolutionCode=public class PrintArray{ |
public static void main (String [] args){ | public static void main (String [] args){ | ||
String [] comp1010 = { "Adam", "Bob", "Carl", "David", "Edward"}; //class list for comp 1010 | String [] comp1010 = { "Adam", "Bob", "Carl", "David", "Edward"}; //class list for comp 1010 | ||
Line 85: | Line 85: | ||
return reversed; | return reversed; | ||
} | } | ||
− | |||
}} | }} |
Revision as of 12:00, 9 April 2010
Back to the Program-A-Day homepage
ProblemToday we'll look at sending an array to a different method, modifying the array, and returning the array to the original method.
public class PrintArray{ public static void main (String [] args){ String [] comp1010 = { "Adam", "Bob", "Carl", "David", "Edward"}; String [] comp1020 = { "Amy", "Beth", "Cindy", "Dawn", "Ellen"}; String [] comp1260 = { "Mike", "Mary", "Matthew", "Megan", "Moe"}; System.out.println("COMP 1010:"); printArray(comp1010); System.out.println("COMP 1020:"); printArray(comp1020); System.out.println("COMP 1260:"); printArray(comp1260); System.out.println("--End of Processing--"); } public static void printArray(String [] courseList){ for (int i=0; i<courseList.length;i++){ System.out.println(courseList[i]); } System.out.println(); } }Use the printArray method to print out the class lists in their original order, and then in reversed order. |
Arrays and Methods
| |
---|---|---|
SolutionTo make your reverseArray method work, use a for loop to cycle through a second array from start to finish, and use a seperate int, decrimented each loop, to cycle through the original array from end to start. In each iteration of the loop, copy the entry from the old array to the new one, and return the new array. | ||
Code |