繁体   English   中英

Java程序运行时错误ArrayIndexOutofBounds

[英]Java program runtime error ArrayIndexOutofBounds

这是我的代码。 我不知道怎么了。 我的项目是创建一个程序来检查单词是否是回文。

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!");
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM