Array Index Out of Bounds Exception (Java)

前端 未结 4 1991
别那么骄傲
别那么骄傲 2020-12-03 23:06

Here is my code:

public class countChar {

    public static void main(String[] args) {
        int i;
        String userInput = new String();

        user         


        
4条回答
  •  悲&欢浪女
    2020-12-03 23:38

    This is Very Good Example of minus Length of an array in java, i am giving here both examples

     public static int linearSearchArray(){
    
       int[] arrayOFInt = {1,7,5,55,89,1,214,78,2,0,8,2,3,4,7};
       int key = 7;
       int i = 0;
       int count = 0;
       for ( i = 0; i< arrayOFInt.length; i++){
            if ( arrayOFInt[i]  == key ){
             System.out.println("Key Found in arrayOFInt = " + arrayOFInt[i] );
             count ++;
            }
       }
    
       System.out.println("this Element found the ("+ count +") number of Times");
    return i;  
    }
    

    this above i < arrayOFInt.length; not need to minus one by length of array; but if you i <= arrayOFInt.length -1; is necessary other wise arrayOutOfIndexException Occur, hope this will help you.

提交回复
热议问题