0

enter image description here

I am getting exception Array Index Out of Bounds error. I am declaring integer i, j. Taking the input from the user how many character he wanted to insert in array. Which is in "i". Now within "j" I asked user to insert the character. Now within loop depending upon the value of j one by one value have to be inserted inside "ch".

import java.util.Scanner;

class EvenOddInArray
{
public static void main(String arg[]){
        int i, j;

        System.out.println("Enter no of integer you wanted to input");
        Scanner obj1 = new Scanner(System.in);

         j  = obj1.nextInt();
        System.out.println("Enter a char");

        Scanner obj = new Scanner(System.in);

        char ch[] = new char[j] ;
        for(i=0;i<j;i++){

        ch[i] = obj.next().charAt(i);

        }           

}
}

]2

Armaan
  • 77
  • 2
  • 6
  • I think you need to do two things: (1) move `obj.next()` out of your `for` loop and put if before it so that you do it only once; (2) check the input does indeed have `j` characters before trying to get `j` characters from it. – dave Oct 17 '18 at 03:56
  • if you are expecting user to entr only single character per line, you should be doign ch[i] = obj.next().charAt(0); since you are using obj.next().charAt(i), for the first line it expects a single char, for second there shoudl be 2 chars and so on..as you are increasing i by one for each iteration – akshaya pandey Oct 17 '18 at 04:02
  • @akshayapandey It works as per your suggestion. Inside the loop I updated the statements like:- str[i] = obj.next().charAt(0);. But my question is if I would take str[i] = obj.next().charAt(i); inside loop why the exception got generated. – Armaan Oct 18 '18 at 02:28
  • the exception gets generated if the length of string which you enter is less than size of i. Eg: if the 3rd string you enter has only two characters. – akshaya pandey Oct 18 '18 at 15:22

0 Answers0