首页 > 解决方案 > 有人可以帮我纠正java pangram程序中的这个错误吗

问题描述

我的 java 代码有问题,但我无法检测到。我错了一个检查 pangram 的代码。Eveything 看起来不错,但我的代码无法编译和运行。这是我得到的错误。线程“主”java.lang.ArrayIndexOutOfBoundsException 中的异常:pangram.Pangram.main 的 42(Pangram.java:29)

package pangram;

import java.util.Scanner;

public class Pangram {
    public static void main(String[] args) {
        //take input from the user
        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter a word or sentence:");
        String sentence=scan.nextLine();
        //String sentence = "the quick brown fox jumps over lazy dog";
        String sentence1=sentence.replace(" ", "");
        //extract data from the object and place in an array x
        char x[]=sentence1.toCharArray();
        int size=x.length;

        //initialize another array with zeros to fill the 26 positions of A-Z
        int y[]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

        //loop through the array using while loop
        int i;
        for(i=0;i<=size;i++){
            int indexOfLetter=x[i]-65;
            //if you find the letter matching, replace 0 with 1 at that postion
            y[indexOfLetter]=1;
            ++i;
        }
        //here check if its indeed a pangram
        i=0;
        while(i!=26){ //26 is the number of letters in alphabet A-Z
            if(y[i]==1){
                i++;
            }else{
                System.out.println("NO");
            }

        }
        System.out.println("YES");

    }

}

标签: java

解决方案


首先, i 必须小于 size,其次不要在 for 循环中增加 i,它在每次迭代后增加。

一种可能的解决方案

Scanner scan = new Scanner(System.in);

System.out.println("Please enter a word or sentence:");
String sentence = scan.nextLine();
String sentence1 = sentence.toLowerCase().replace(" ", "");

char[] x = sentence1.toCharArray();
int size = x.length;

//initialize another array with zeros to fill the 26 positions of A-Z
int[] y = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

//loop through the array using while loop
for(int i=0; i < size; i++){
    int indexOfLetter = x[i] - 'a';
    //if you find the letter matching, replace 0 with 1 at that postion
    y[indexOfLetter]=1;
}
//here check if its indeed a pangram
boolean pangram = true;
for (int i = 0; i < 26 && pangram; i++) {
    if (y[i] == 0) {
       pangram = false
    }
}

System.out.println(pangram ? "YES" : "NO");

推荐阅读