java - 有人可以帮我纠正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");
}
}
解决方案
首先, 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");
推荐阅读
- unity3d - 如何在 Unity 中从目标对象后面跟踪摄像机
- c++ - getch() 返回 2 个字符
- javascript - 令牌无效错误:指定的令牌无效:无法读取未定义的属性“替换”?
- java - 我的 toString junit 测试失败,我有一个几乎相同的 toString junit 测试运行良好,我不知道问题是什么
- python - 无法在电报机器人中转发消息
- docker - 如何删除(已删除)docker-container的docker-volume?
- azure - 从不同订阅的另一个 azure 容器存储库 (ACR) 引用 docker 映像
- pandas - 使用多索引列连接两个 pandas 数据框
- google-play-console-beta - 从 Google Play 控制台下载 APK(测试版)
- java - 如何在 Java 的 get 和 return 方法中使用 input(int)?