gpt4 book ai didi

java - 回文编码

转载 作者:行者123 更新时间:2023-12-02 07:08:33 24 4
gpt4 key购买 nike

我正在尝试使用一种方法在java中创建一个回文测试器..这就是我到目前为止所拥有的。它是如此接近,我只是不明白为什么它不会说它是回文并将其反转。

System.out.println("Fun with Palindromes!!");

Scanner in = new Scanner(System.in);
System.out.println("Enter the potential palindrome (or enter exit to quit): ");
String x = in.nextLine();

while(!x.equals("exit"))
{
String t = x.toLowerCase();
String u = CleanUpString(t);
Boolean wordCheck = checkPalindrome(u);
int wordCount = x.length();

String rev = "";

for(int i = 0; i <x.length(); i++)
{
rev = x.charAt(i)+rev;
}
if(wordCheck == true)
{
System.out.println("The orginal string\"" + u + "\" contains" + wordCount + "characters." );
System.out.println("The converted string\"" + rev + "\"is a palindrome");
}
else if(wordCheck == false)
{
System.out.println("The string \"" + u + "\" contains " + wordCount + " characters");
System.out.println("\"" + rev + "\" is not a palindrome");
}
System.out.println("\nEnter the potential palindrome, or enter exit to quit: ");
x = in.nextLine();

}
}
public static String CleanUpString(String words)
{
words = words.replace(".","");
words = words.replace("," ,"");
words = words.replace(":","");
words = words.replace("!","");
return words;


}



public static boolean checkPalindrome(String baseball)
{
String rev = "";
for(int i = 0; i<baseball.length()-1; i++)
{
rev = baseball.charAt(i) + rev;

}
if(rev.equals(baseball))
return true;
else
return false;

}

}

最佳答案

这是我用来判断一个字符串是否是回文字符串的代码:

private static boolean checkPalindrome(String str){
if (str == null)
return false;
int len = str.length();
for (int i=0;i<len/2 ; i++){
if (str.charAt(i) != str.charAt(len - i - 1)){
return false;
}
}
return true;
}

要反转字符串,您可以简单地使用:

String reverse = new StringBuffer(string).reverse().toString();

希望这些可以帮助到你。

关于java - 回文编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15816878/

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