0

I am trying to make an array of type string of which the size and strings are inputted by the user and i keep getting error ArrayIndexOutOfBoundsException There is similar threads i found pertaining to this but none of which have solved this error. in my for statement if i take out the equal to and just do less than i receive no errors but i can only input one name less than the number i input. If i leave the code as is everything appears to work as it should minus the error. I understand i am getting this fault because my array is going out of bounds but i cant figure out why. please help! thank you!

package sales;
import compare.*;  
import java.util.*;

public class Sales {
   public static void main(String[] args) {

        Scanner scan=new Scanner(System.in);
        System.out.println("Enter number of employees to compare:");
        int numEmp = scan.nextInt();

        while(numEmp < 2){
            System.out.println("Has to be at least 2 employees:");
            numEmp = scan.nextInt();
        }

        String[] names = new String[numEmp];

        System.out.println("Enter employees name:");
        for(int i=0;i<=names.length;i++){
            names[i]=scan.nextLine();    
        }
    }
}
dumbPotato21
  • 5,669
  • 5
  • 21
  • 34
Zachary
  • 7
  • 3

1 Answers1

0

Change the condition of the for to i<names.length instead of i<=names.length.

scan.nextLine(); //add this
for(int i=0;i<names.length;i++){
    names[i]=scan.nextLine();
}
dumbPotato21
  • 5,669
  • 5
  • 21
  • 34