0

I have a scenario,where In need to search values in an Array..the array might consist of elements with space.

In the below code:- I will enter the size of the array in the console, where as the code skipping the last entry,If have entered the array size as 5 it is considering only 4 rows

    Scanner scan = new Scanner(System.in);
    int n  = scan.nextInt();
    String [] nameArr = new String[n];
    for(int i=0;i <n;i++)
    {

     nameArr[i] = scan.nextLine();

    }

    System.out.println("Enter the name you want to search");
    String search = scan.nextLine();

When I change it as the below

for(int i=0;i <=n;i++)

I am getting the below Exception Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at Array2list.main(Array2list.java:18)

LearnerLaksh
  • 25
  • 1
  • 5
  • Add `scan.nextLine()` after your `nextInt()` call. See https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo?rq=1 – Zircon Jul 17 '18 at 15:56
  • just a side note, use i < nameArr.length(); instead of i < n. – RAZ_Muh_Taz Jul 17 '18 at 16:02

0 Answers0