目前正在尝试编写一个诗歌回文检查器。这并不是专门针对回文,而是数组中的单词在两种情况下都具有相同的顺序。例如下面是一首回文诗
Life-
imitates nature,
always moving, traveling continuously.
Continuously traveling, moving always,
nature imitates
life
我的问题是迭代数组以匹配第一个和最后一个元素,因为目前它以错误的顺序比较事物。
我的代码如下:
import java.util.Scanner;
import java.io.*;
public class WordPalindromeTest {
public static void main(String[] args) {
System.out.println("This program determines if an entered sentence/word poem is a palindrome.");
Scanner input = new Scanner(System.in);
System.out.println("Please enter a string to determine if it is a palindrome: ");
while(input.hasNextLine()) {
String palin = input.nextLine();
if(palin.equals("quit")) {
break;
}
else {
boolean isPalin = isWordPalindrome(palin);
if(isPalin == true) {
System.out.println(palin + " is a palindrome!");
}
else
System.out.println(palin + " is NOT a palindrome!");
}
}
System.out.println("Goodbye!");
input.close();
}
public static boolean isWordPalindrome(String s) {
boolean isWordPal = false;
String lowerCase = s.toLowerCase();
String replaced = lowerCase.replaceAll("[^a-zA-Z0-9\\s]", "");
String words[] = replaced.split(" ");
for(int i = 0; i < words.length; i++) {
for(int j = 0; j < words.length; j++) {
if (words[i].equals(words[j]) && i != j) {
isWordPal = true;
}
else
isWordPal = false;
}
}
return isWordPal;
}
}
具体问题是
public static boolean isWordPalindrome(String s) {
boolean isWordPal = false;
String lowerCase = s.toLowerCase();
String replaced = lowerCase.replaceAll("[^a-zA-Z0-9\\s]", "");
String words[] = replaced.split(" ");
for(int i = 0; i < words.length; i++) {
for(int j = 0; j < words.length; j++) {
if (words[i].equals(words[j]) && i != j) {
isWordPal = true;
}
else
isWordPal = false;
}
}
return isWordPal;
}
我对如何正确设置循环来比较正确的元素感到困惑。它应该将第一个元素与最后一个元素进行比较,将第二个元素与倒数第二个元素进行比较,依此类推,直到循环完成。我意识到在继续之前我已经将第一个数组与整个数组进行了比较。
最佳答案
这看起来像是一项家庭作业,所以我不会给你一个可行的解决方案。但它是这样的:
-您不需要两个循环。您只需比较第一个与最后一个、第二个与倒数第二个等。(提示:如果您从 Array
的长度中减去 i-1
您将获得需要比较的 i
对应的元素)。此外,您只需要迭代 Array
长度的一半以上
-如果 isWordPal
变为 false,您需要返回
false。否则它可能会被覆盖,最后它会返回 true。
关于Java诗歌回文检查器: Iterate through array matching elements in order,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52358900/