Results 1 to 3 of 3
Thread: Array in Method Help
- 12-06-2012, 04:22 AM #1
Member
- Join Date
- Dec 2012
- Posts
- 9
- Rep Power
- 0
Array in Method Help
I need help with this code. I'm not getting any errors, but it's not doing what I want it to. I want it to add five to each value in the ethan array, but it does not. I am able to get it to work with a regular for loop, but not an enhanced one (at line 21). Does Java handle values in arrays differently in enhanced for loops than in normal ones?
Java Code:package arrayspractice; public class Apple { public static void main(String[] args) { int ethan[] = {3,4,5,6,7}; change(ethan); for (int y: ethan){ System.out.println(y); } } public static void change(int x[]) { for (int c: x) { c+=5; } } }Last edited by ETBunce; 12-06-2012 at 04:24 AM.
- 12-06-2012, 04:32 AM #2
Senior Member
- Join Date
- Jun 2007
- Location
- Bali, Indonesia
- Posts
- 696
- Rep Power
- 6
Re: Array in Method Help
In your code you didn't manipulate the values in the array. Instead you iterate the array, take the values from the array and then you add that value with 5. The original array is not touched at all. If you want to manipulate the array you need to set the new value back to the array.
So you can code it like:
Java Code:public static void change(int[] x) { for (int i = 0; i < x.length; i++) { x[i] = x[i] + 5; } }Website: Learn Java by Examples
- 12-06-2012, 04:38 AM #3
Member
- Join Date
- Dec 2012
- Posts
- 9
- Rep Power
- 0
Similar Threads
-
Need help with add method for array.
By RozenKristal in forum New To JavaReplies: 3Last Post: 10-15-2012, 04:38 AM -
Returning Array from a method
By Manfizy in forum Advanced JavaReplies: 3Last Post: 04-04-2012, 12:01 PM -
help writing array method
By katiebear128 in forum New To JavaReplies: 3Last Post: 10-16-2011, 05:31 PM -
I want to make an array in a method...
By nhmllr in forum New To JavaReplies: 7Last Post: 10-02-2011, 08:18 AM -
Passing an array to a method.
By twcast in forum New To JavaReplies: 9Last Post: 02-10-2010, 09:13 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks