-2

Im trying to receive 5 products prices and 5 product's names by separates arrays and print at the end, so im correcting the errors till this error appears : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at javaapplication3.JavaApplication3.main(JavaApplication3.java:23)

thats the final boss for me(sorry about this post being closed)

package javaapplication3;

import java.util.Scanner;

public class JavaApplication3 {


   public static void main(String[] args) {

       Scanner read = new Scanner(System.in);
       double n [] = new double [5];
       String name[] = new String[5];
       double media;    
       int contar=0;
        for(int counter=0; counter<=n.length; counter++)
        {
           System.out.println("Type the product "+counter+ " price");
          n[counter] = read.nextDouble();
         
       }
         
        for(int i =0; i<=name.length;i++)
        {
           System.out.println("Type the product "+n[i]+" name");
           name[i] = read.nextLine();
       }
       while(contar<=5)
       {
           System.out.println(n[contar]);
           if(n[contar]<=50)
           {
               System.out.println("The "+name[contar]+" costs" +n[contar]);
           }
           media = n [contar]/5;
           contar++;

       }
       
       
       
       
   }
}
  • 2
    Does this answer your question? [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – OH GOD SPIDERS Jun 08 '21 at 14:40
  • 3
    You are declaring your `name[]` to have a length of 5, meaning it will have the indexes 0, 1, 2, 3 and 4 available. Inside your loop your are however trying to fill indexes 0 to 6. Since there is no index 5 or 6 your program doesn't just end, but it throws a RuntimeException. In more common terms: You made an error and your program crashes because of that error. – OH GOD SPIDERS Jun 08 '21 at 14:44
  • thanks, thats make sense – Luiz Gustavo Jun 09 '21 at 21:34

1 Answers1

1

I dont know what you are trying to do but in the second and third loop you are not updating the counter variable so it will cause an infinite loop.

In the second loop you are incrementing counter but the variable that controls the loop is i, and in the third one you are incrementing also counter but the variable name is contar.

Your second and third loops should look like

while (i<=6)
       {
           System.out.println("Type the product "+n[i]+" name");
           name[i] = read.nextLine();
           i++;
       }
while(contar<=6)
       {
           System.out.println(n[contar]);
           if(n[contar]<=50)
           {
               System.out.println("The "+name[contar]+" costs" +n[contar]);
           }
           media = n [contar]/5;
           contar++;
       }
JArgente
  • 2,239
  • 1
  • 9
  • 11