0

I went over this code over and over, but somehow I get ''array out of bounds''. I started the for loop at one, because I want to have Car 1 and starting at Car 0 doesn't make sense. But somehow my array get out of bounds and the only solution I had was adding +1 at my arrays, but that is not a good solution. So I removed that +1. How should I adjust the code so it doesn't get out of bounds?

The Code:

    public static void main(String[] args) {
Scanner input = new Scanner (System.in);
// Ask the user for maximum speed in km / h (integer) at the measuring site
System.out.print( "What is the maximum speed at the measuring site (km / h)? ");
 int MaxSpeed = input.nextInt ();
 // Ask the user for the number of cars will be fined
 System.out.print( "How many cars have driven too fast? ");
int amountCars = input.nextInt ();
// Create three arrays to store the data about cars
String [] licensePlates = new String [amountCars ];
int [] measureSpeed = new int [amountCars];
double [] fines = new double [amountCars];
 for (int i = 1; i <= amountCars; i++) {
 Scanner scanner = new Scanner(System.in);
 do {
 // Ask the user by car to the license plate and the measured speeds
 System.out.println ( " ");
 System.out.println ( "Car " + i);
 System.out.print ( "License plate: ");
 licensePlates[i] = scanner.nextLine ();
 System.out.print ( "measured speed: ");
 measureSpeed[i] = scanner.nextInt ();
if (measureSpeed [i] <MaxSpeed) {
System.out.println ( "Please enter a speed above the speed limit.");
}
} while (measureSpeed [i] <MaxSpeed); {
}
 }
    }
}
Tony Stark
  • 45
  • 1
  • 8
  • But also http://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo – Sotirios Delimanolis Dec 24 '16 at 20:48
  • Arrays start at index `0` and end at index `n-1`, so your loop `for (int i = 1; i <= amountCars; i++)` should be `for (int i = 0; i < amountCars; i++)`, otherwise you ignore the first element (index `0`) and access index `amountCars`, which does not exist. The last index is `amountCars - 1`. – thatguy Dec 24 '16 at 20:53
  • Well if I do that it will start at Car 0 and I don't want that lol. – Tony Stark Dec 24 '16 at 21:00

0 Answers0