gpt4 book ai didi

java - 如何将 char 数组传递给方法并返回 boolean 值

转载 作者:行者123 更新时间:2023-12-02 05:05:52 25 4
gpt4 key购买 nike

我正在尝试编写一个程序来检查一个单词是否是回文。我的代码可以编译,但 isItPalindrome 方法中的代码似乎根本没有运行。我希望有人能指出我哪里出错了。这是我的代码:

class Main
{
public static void main ( String args[] )
{
System.out.print ("#Enter word");
String word = BIO.getString();

String wordLowerCase = word.toLowerCase(); // converts word to lower case (only way i could think of to ignore case)
char letters[] = wordLowerCase.toCharArray(); // converts string into an array of character


while ( !word.equals ("END")){
if (isItPalindrome(letters) == true)
{
System.out.print (""+word+"");
System.out.println (" is a palindrome");

}
else if (isItPalindrome(letters) == false)
{
System.out.print (""+word+"");
System.out.println (" is not a palindrome");
}

System.out.print ("#Enter word");
word = BIO.getString();

}

}

public static boolean isItPalindrome ( char letters[]){

boolean palindrome = true;
if (letters.length%2 == 0){
for (int index=0; index<letters.length/2-1; index++) //index will finish at letters/2
{
if (letters[index] != letters[letters.length-index-1]) //checks if index is the same as its opposite letter
{
return false;

}
else //if any pairs of letters are not in ascending order then it returns fasle and breaks out of the loop
{
palindrome = true;

}

}
}
else{
for (int index = 0; index < (letters.length-1)/2-1; index++)
{
if (letters[index] != letters[letters.length-index-1]){

return false;

}
else{

palindrome = true;
}

}
}

return palindrome;
}

}

最佳答案

主方法中存在一些问题,例如字符数组从未更新,回文方法过于复杂,这是工作版本:

public static void main(String args[]) {
System.out.print("#Enter word: ");
String word = BIO.getString();

while (!word.equals("END")) {
char[] letters = word.toLowerCase().toCharArray();

if (isItPalindrome(letters) == true) {
System.out.println(word + " is a palindrome");
} else {
System.out.print(word + " is not a palindrome");
} // OR
// Use this one-liner instead of the if:
// System.out.println(word + isItPalindrome(letters) ?
// " is a palindrome" : " is not a palindrome");

System.out.print("#Enter word: ");
word = BIO.getString();
}

}

public static boolean isItPalindrome(char letters[]) {
for (int i = 0; i < letters.length / 2; i++) {
if (letters[i] != letters[letters.length - i - 1]) {
return false;
}
}

return true;
}

希望这有帮助。

关于java - 如何将 char 数组传递给方法并返回 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27803439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com