Results 1 to 3 of 3
  1. #1
    Join Date
    Mar 2011
    Posts
    21
    Rep Power
    0

    Default Some problem with the array

    Hi Guys,

    Please check the following piece of code for me.

    Java Code:
    public class Test {
    
    	public static void main(String args[]) {
    
    		int num[] = { 2, 4, 6, 8 };
    
    		int change[] = change(num);
    
    		for (int y : change) {
    			System.out.println(y);
    		}
    	}
    
    	public static int[] change(int x[]) {
    		int i = x.length;
    		x[i + 1] = 10;
    
    		return x;
    	}
    }
    I just want to add one more integer value say 10 at the end of the existing array. I just want to know whether is that logic correct or not. I am getting the following error

    Java Code:
    "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
    	at Test.change(Test.java:16)
    	at Test.main(Test.java:7)"
    Please erply me as soon as possible. Thanks in advannce.

    Regards

    Naveen Paul
    Last edited by pbrockway2; 01-03-2012 at 05:53 AM. Reason: code tags added

  2. #2
    Join Date
    Mar 2011
    Posts
    21
    Rep Power
    0

    Default Re: Some problem with the array

    I can add values to the existing values in the array.

    Java Code:
    public class Test {
    
    	public static void main(String args[]) {
    
    		int num[] = { 2, 4, 6, 8 };
    
    		int change[] = change(num);
    
    		for (int y : change) {
    			System.out.println(y);
    		}
    	}
    
    	public static int[] change(int x[]) {
    		for(int i=0;i<x.length;i++){
    			x[i]+=5;
    		}
    		return x;
    	}
    }
    Is it possible to add another value at the end of the array?
    Last edited by pbrockway2; 01-03-2012 at 05:54 AM. Reason: code tags added

  3. #3
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default Re: Some problem with the array

    "An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed." More at Arrays (The Java™ Tutorials > Learning the Java Language > Language Basics)

    -----

    Formatted code is much more readable: See Posting faq and Tag faq

Similar Threads

  1. Replies: 0
    Last Post: 05-12-2011, 08:04 PM
  2. Array problem please help
    By newToJava3 in forum New To Java
    Replies: 2
    Last Post: 12-15-2010, 01:38 PM
  3. array problem
    By jabo in forum New To Java
    Replies: 2
    Last Post: 03-31-2010, 10:54 AM
  4. Array problem
    By binarzt in forum New To Java
    Replies: 5
    Last Post: 02-14-2010, 10:01 AM
  5. array problem
    By oceansdepth in forum New To Java
    Replies: 3
    Last Post: 04-05-2008, 03:25 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
  •