4 Replies - 527 Views - Last Post: 05 November 2010 - 10:43 AM Rate Topic: -----

#1 <3DIC  Icon User is offline

  • D.I.C Regular


Reputation: 6
  • View blog
  • Posts: 327
  • Joined: 06-October 10

out of bounds exception

Posted 05 November 2010 - 10:19 AM

Why am i getting this out of bounds error:


10.0
9.0
8.0
7.0
6.0
5.0
4.0
3.0
2.0
1.0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1


with my code:

import java.util.Scanner;

public class Array
{
   public static void main (String args[]) 
	{	
		float [] carrier = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f};
		
		for(int i = 9; i < carrier.length; i--)
			System.out.println(carrier[i]);
	
	} // end main
} // end class

This post has been edited by <3DIC: 05 November 2010 - 10:20 AM


Is This A Good Question/Topic? 0
  • +

Replies To: out of bounds exception

#2 Moshambi  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 8
  • View blog
  • Posts: 280
  • Joined: 20-November 07

Re: out of bounds exception

Posted 05 November 2010 - 10:21 AM

Well the problem it seems to me is that your condition for your for loop will always be true since you are decreasing the value of it.
Was This Post Helpful? 1
  • +
  • -

#3 <3DIC  Icon User is offline

  • D.I.C Regular


Reputation: 6
  • View blog
  • Posts: 327
  • Joined: 06-October 10

Re: out of bounds exception

Posted 05 November 2010 - 10:30 AM

Beside doing throwing this in my loop:

if(i < 0)
  break;



Is there a better way of doing this or stating my for loop?
Was This Post Helpful? 0
  • +
  • -

#4 javadork  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 32
  • View blog
  • Posts: 135
  • Joined: 21-August 10

Re: out of bounds exception

Posted 05 November 2010 - 10:40 AM

How about switching this around

for (int i = carrier.length - 1; i >= 0; i--)



[Edited: Oops, my bad, goofed on the condition. thx SarumanTheWhite, +1 to you.]

This post has been edited by javadork: 05 November 2010 - 10:48 AM

Was This Post Helpful? 0
  • +
  • -

#5 SarumanTheWhite  Icon User is offline

  • D.I.C Regular

Reputation: 73
  • View blog
  • Posts: 352
  • Joined: 04-November 08

Re: out of bounds exception

Posted 05 November 2010 - 10:43 AM

Changing the condition in your for loop to i >= 0 would be better.
Was This Post Helpful? 2
  • +
  • -

Page 1 of 1