Difference between revisions of "ReverseArray Method"
m (Added closing bracket in SolutionCode.) |
(Added quotations to student quotes) |
||
(3 intermediate revisions by 3 users not shown) | |||
Line 10: | Line 10: | ||
− | + | {{CodeBlock | |
+ | |Code=public class PrintArray{ | ||
public static void main (String [] args){ | public static void main (String [] args){ | ||
String [] comp1010 = { "Adam", "Bob", "Carl", "David", "Edward"}; | String [] comp1010 = { "Adam", "Bob", "Carl", "David", "Edward"}; | ||
Line 34: | Line 35: | ||
} | } | ||
} | } | ||
− | + | }} Use the printArray method to print out the class lists in their original order, and then in reversed order. | |
− | |SideSectionTitle= | + | |SideSectionTitle=...By Students |
− | |SideSection= | + | |SideSection= |
− | + | ||
+ | "This problem was actually given to me during an interview for computer science coop. | ||
+ | The question was a little more complicated, but it came down to reversing strings, the more difficult part was to do it "in place". Surprisingly, I had a hard time remembering how to do this! | ||
+ | It just goes to show you, what you learn in Comp 1010 is very relevant and will come back to haunt you in the future!" | ||
Latest revision as of 15:32, 8 December 2011
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. |
...By Students"This problem was actually given to me during an interview for computer science coop. The question was a little more complicated, but it came down to reversing strings, the more difficult part was to do it "in place". Surprisingly, I had a hard time remembering how to do this! It just goes to show you, what you learn in Comp 1010 is very relevant and will come back to haunt you in the future!" | |
---|---|---|
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 |