gpt4 book ai didi

java - 有人可以帮我纠正 java pangram 程序中的这个错误吗

转载 作者:行者123 更新时间:2023-12-02 09:14:52 25 4
gpt4 key购买 nike

我的 java 代码有问题,但我无法检测到。我错误地检查了全语法的代码。一切看起来都很顺利,但我的代码无法编译和运行。这是我得到的错误。线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException:42 在 pangram.Pangram.main(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");

}

}

最佳答案

首先,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");

关于java - 有人可以帮我纠正 java pangram 程序中的这个错误吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59085635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com