d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Why Is There An Array Out Of Bounds Exception?
Add Reply New Topic New Poll
Member
Posts: 10,049
Joined: Aug 11 2014
Gold: 540.00
Oct 21 2015 06:29pm
Scanner keyboard = new Scanner(System.in);

double[] score = new double[5];
int x;
double max;

System.out.println("Enter " + score.length + " scores: ");
score[0]=keyboard.nextDouble();

max = score[0];

for (x=1;x<score.length;x++)

{
score[x]=keyboard.nextDouble();

if(score[x]>max)
max=score[x];
}

System.out.println("highest score is " + score[x]);

}
}

literally can't figure out why
Member
Posts: 32,925
Joined: Jul 23 2006
Gold: 3,804.50
Oct 21 2015 06:34pm
do you know how the for loop works? print out the x after you exit the loop. what do you expect x to be?
Member
Posts: 29,352
Joined: Mar 27 2008
Gold: 504.69
Oct 21 2015 06:40pm
The for loop fails when x is 5. Outside of the loop you are trying to print score[5] which is out of bounds.

Edit

The highest score is also max not score[x]

This post was edited by ROM on Oct 21 2015 06:42pm
Member
Posts: 23,862
Joined: Aug 16 2006
Gold: 20.00
Oct 21 2015 06:40pm
Quote (kyle_lowry2 @ Oct 21 2015 07:29pm)
Scanner keyboard = new Scanner(System.in);

double[] score = new double[5];
int x;
double max;

System.out.println("Enter " + score.length + " scores: ");
score[0]=keyboard.nextDouble();

max = score[0];

for (x=1;x<score.length;x++)

{
score[x]=keyboard.nextDouble();

if(score[x]>max)
max=score[x];
}

System.out.println("highest score is " + score[x]);

}
}

literally can't figure out why


iterate through that loop on paper


x = 1....< score.length(5)? true -> NEXT
x = 2....< score.length(5)? true -> NEXT
x = 3....< score.length(5)? true -> NEXT
x = 4....< score.length(5)? true -> NEXT
x = 5....< score.length(5)? FALSE -> EXIT LOOP

x is now 5

do you see now?


edit: slow to the trigger as usual

This post was edited by Eep on Oct 21 2015 06:41pm
Member
Posts: 10,049
Joined: Aug 11 2014
Gold: 540.00
Oct 21 2015 07:43pm
ohh thank you guys! got it!
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll