Results 1 to 2 of 2
  1. #1
    jean28 is offline Member
    Join Date
    Aug 2012
    Posts
    16
    Rep Power
    0

    Default Why do I get an out of boundaries here?

    Is there any particular reason why I should get an out of boundaries error when I run this code?

    Java Code:
    public class Distance {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    
    		
    		//int[] a = new int[6];
    		int[]a = {1,5,9,7,4};
    		
    		int[] pair = new int[2];
    		
    		pair =  MinDistance(a);
    		System.out.println("La distancia del elemento  "+pair[0]+"  elemento  "+pair[1]+"  es la distancia minima");
    		System.out.println("Distancia minima es: "+ (Distance.distanceCalc(pair[0], pair[1])) );
    		}
    	
    	
    	
    
    	public static int[] MinDistance(int[] matrix){
    
    		int[] a = matrix;
    		
    		int[] pair = new int[2];
    		double minDistance = distanceCalc(a[0],a[1]);
    		int k = 0;
    		
    		
    		
    		for (int j=0 ; j<a.length;j++){
    			
    			k++;
    			double newDistance = distanceCalc(a[j],a[k]);
    			
    			
    			if (newDistance< minDistance){
    				minDistance = newDistance;
    				pair[0]=j;
    				pair[1]=k;
    				}
    			
    		}
    		return pair;
    	}
    
    
    
    	public static double distanceCalc(double a , double b){
    		double distance = Math.sqrt((a-b)*(a-b));
    		return distance;	
    	}
    
    }

    I get this error:
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
    at Distance.MinDistance(Distance.java:37)
    at Distance.main(Distance.java:16)

  2. #2
    SJF
    SJF is offline Senior Member
    Join Date
    Oct 2012
    Posts
    108
    Rep Power
    0

    Default Re: Why do I get an out of boundaries here?

    Your counter k.

    j = 0 -> length-1
    so ....
    k = 1 -> length

    array[array.length] = Out Of Bounds!

Similar Threads

  1. How do you go about setting boundaries in a game?
    By robertbob in forum New To Java
    Replies: 6
    Last Post: 05-10-2010, 11:24 PM

Posting Permissions

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