- 列表項
我在Java中創建一個迴文程序,它通過用戶輸入的字或詞,並將它們放入一個數組。然後它接受反向輸入並將其放入另一個數組中。然後我檢查兩個字是否相同。迴文程序沒有給予正確的輸出在Java中
我的問題是,程序正在改變其中一個字母,以便它總是正確的,並且它迭代了太多次。任何想法,在我的代碼是什麼造成這個?
public static boolean isPalindrome(char[] a, int used){
char[] original = a;
int newNumber = used - 1;
for(int i = 0; i <= newNumber; i++){
a[i] = a[newNumber - i ];
System.out.println("Your original word was: " + String.valueOf(original));
System.out.println("Backwards, your word is: " + String.valueOf(a));
}
if(String.valueOf(original).equalsIgnoreCase(String.valueOf(a))){
System.out.println("Your word or words are palindromes.");
}else{
System.out.println("Your word or words are not palindromes");
}
return(String.valueOf(original).equalsIgnoreCase(String.valueOf(a)));
}
public void userInput(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a word or words that you believe are palindromes: ");
word = keyboard.next();
word = word.replaceAll("\\W","");
int length = word.length();
char[] p = new char[length];
for(int i = 0; i < length; i++){
p[i] = word.charAt(i);
}
Palindrome.isPalindrome(p, length);
}
這是我的輸出,當我輸入 「糖果」。
Your original word was: yandy
Backwards, your word is: yandy
Your original word was: ydndy
Backwards, your word is: ydndy
Your original word was: ydndy
Backwards, your word is: ydndy
Your original word was: ydndy
Backwards, your word is: ydndy
Your original word was: ydndy
Backwards, your word is: ydndy
Your word or words are palindromes
感謝大家的回答! 下面是正確的代碼這樣的作品,雖然效率不高,因爲它可以:
public static boolean isPalindrome(char[] a, int used){
char[] original = a;
char[] newArray = new char[used];
int newNumber = used - 1;
for(int i = 0; i <= newNumber; i++){
newArray[i] = a[newNumber - i ];
}
System.out.println("Your original word was: " + String.valueOf(original));
System.out.println("Backwards, your word is: " + String.valueOf(newArray));
if(String.valueOf(original).equalsIgnoreCase(String.valueOf(newArray))){
System.out.println("Your word or words are palindromes.");
}else{
System.out.println("Your word or words are not palindromes");
}
return(String.valueOf(original).equalsIgnoreCase(String.valueOf(newArray)));
}
那麼什麼是你的輸出? – SimplyPanda