Results 1 to 3 of 3
  1. #1
    ETBunce is offline Member
    Join Date
    Dec 2012
    Posts
    11
    Rep Power
    0

    Default 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.

  2. #2
    wsaryada is offline Senior Member
    Join Date
    Jun 2007
    Location
    Bali, Indonesia
    Posts
    757
    Rep Power
    7

    Default 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;
        }
    }

  3. #3
    ETBunce is offline Member
    Join Date
    Dec 2012
    Posts
    11
    Rep Power
    0

Similar Threads

  1. Need help with add method for array.
    By RozenKristal in forum New To Java
    Replies: 3
    Last Post: 10-15-2012, 04:38 AM
  2. Returning Array from a method
    By Manfizy in forum Advanced Java
    Replies: 3
    Last Post: 04-04-2012, 12:01 PM
  3. help writing array method
    By katiebear128 in forum New To Java
    Replies: 3
    Last Post: 10-16-2011, 05:31 PM
  4. I want to make an array in a method...
    By nhmllr in forum New To Java
    Replies: 7
    Last Post: 10-02-2011, 08:18 AM
  5. Passing an array to a method.
    By twcast in forum New To Java
    Replies: 9
    Last Post: 02-10-2010, 09:13 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •