Saturday 25 June 2016

java - Array Index Out Of Bounds Exception





Been looking around to see if anything could help me out but I don't understand much of what people are answering and anything I do understand doesn't seem to solve the issue! So basically as the title says, I'm getting an array index out of bounds exception and I have no idea why. Any help is greatly appreciated.



Code:



import javax.swing.*;

public class Array {
public static void main(String[] args) {
double height[] = new double[10];
String heightAsString;

int i, over18 = 0, under16 = 0;

for(i = 1; i <= height.length; i++){
heightAsString = JOptionPane.showInputDialog("Please Enter The Height Of Person " + i);
height[i] = Double.parseDouble(heightAsString);

if(height[i] > 1.8){
over18 += 1;
}


if(height[i] < 1.6){
under16 += 1;
}
}

JOptionPane.showMessageDialog(null,"The Total Number Of People Over 1.8m Is: " + over18 +
"\nThe Total Number Of People Under 1.6m Is: " + under16);
}
}


Answer



for(i = 1; i <= height.length; i++){
heightAsString = JOptionPane.showInputDialog("Please Enter The Height Of Person " + i);
height[i-1] = Double.parseDouble(heightAsString);

if(height[i-1] > 1.8){
over18 += 1;
}

if(height[i-1] < 1.6){

under16 += 1;
}
}


use height[i-1], because array index starts from 0.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...