-2

I am trying to solve this prompt where you have to detect whether a sentence is a pangram or not. I'm getting an error on line 8 and line 20, saying 'Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 26 out of bounds for length 26.' I am really confused why this error is occurring. Can someone help, I've tried searching this error up. Sorry if my code is really bad, This is my 10th day of Java.

public class Solution {

  public static boolean check(String sentence){
    boolean[] validLetter = new boolean[26];
    System.out.println(validLetter.length);
    for (int i=0; i <= sentence.length(); i++) {
      if ('a' <= sentence.charAt(i) && sentence.charAt(i) <= 'z') {
        validLetter[i] = true;
      }
      else validLetter[i] = false;
    }
    for (int i=0; i <= validLetter.length; i++) {
      if (validLetter[i] == false) return false;
    }
    return true;
    
  }

  public static void main(String[] args) {
    System.out.println(Solution.check("the quick brown fox jumps over the lazy dog"));
  }

}
Shlok Sharma
  • 130
  • 2
  • 9

2 Answers2

0

You should use for (int i=0; i < sentence.length(); i++) in your iterations and not <=.

I'd suggest looking into how to iterate arrays in Java https://www.geeksforgeeks.org/iterating-arrays-java/

CloudBalancing
  • 1,461
  • 2
  • 11
  • 22
0

Array in java and most of programming languages start the index from 0, so when your array length/size is 26 you can access it by array[25].

Please read the documentations :)

Array

edhi.uchiha
  • 366
  • 2
  • 9