Java程序运行时错误ArrayIndexOutofBounds

标签 java

这是我的代码。我不确定出了什么问题。我的项目是创建一个程序来检查一个单词是否是回文。

import java.util.Scanner;

public class PalindromeChecker {
    public static void main(String[] args) {
        // Open Scanner
        Scanner input = new Scanner(System.in);
        // Prompt User for word
        System.out.println("Enter word to check if it is a Palindrome:");
        // Scan in the word
        String word = input.nextLine();
        int a = 0; // used to extract word from array (small)
        int b = 0; // used to extract word from array (large)
        int c = 0; // used to stop when
        int d = (word.length());
        int e = d / 2;
        int f = e - 2;
        int x = word.length(); // set cap of array pulling
        char[] array = word.toCharArray(); // create array of chars
        if (array[a] == array[x] && c != f) {
            a++;
            x--;
            c++;
        } else {
            b = 1;
        }
        if (b == 1) {
            System.out.println("This word is not a Palindrome!");
        } else if (b == 0) {
            System.out.println("This word is a Palindrome!");
        }
    }
}

错误出现在

if (array[a] == array[x] && c!=f)

我不太确定出了什么问题,但是当您输入非回文时,它会跳过。我非常乐意就在这种情况下该怎么做提供一些建议。

最佳答案

由于数组是从 0 开始的,因此最后一个条目的索引长度为 -1。

int x = word.length() - 1

您还缺少一个用于检查单词中所有字符的循环。最后,你似乎有很多多余的变量。以下是修复代码的方法:

    boolean isPalindrome = true;
    for (int n = 0; n < array.length / 2; n++){
        if (array[n] != array[array.length - n - 1]) {
            isPalindrome = false;
            break;
        }
    }
    if (isPalindrome) {
        System.out.println("This word is a Palindrome!");
    } else {
        System.out.println("This word is not a Palindrome!");
    }

关于Java程序运行时错误ArrayIndexOutofBounds,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30970673/

相关文章:

java - 在计算器中识别一元减号,java

java - Android - Sqlite 还是 Xml?

java - 无法在 Gradle 中重新排序 AspectJ 任务

java - 合并排序在复制步骤中抛出 ArrayOutOfBounds 错误?

java - 使用 getParent() 在 CardLayout 中的卡片之间切换

java - 使用 Selenium 从 header (<H></H>) 中获取数据

java - 一次打印一个条目的链表节点 (Java)

java - 检查链表是否为回文(递归)

java - 如何将扫描值存储到数组中?

java - 如何对使用 session 窗口的 kafka 流应用程序进行单元测试