这是我的代码。我不确定出了什么问题。我的项目是创建一个程序来检查一个单词是否是回文。
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/