gpt4 book ai didi

java - 回文识别器

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

我正在学习 Java。我正在构建这个回文识别器并使用两个带有字符的数组,我认为我用我发现的其他东西得到了很好的实现,但我正在绞尽脑汁地理解为什么它到目前为止没有按预期工作。发生了什么:

  • “A Santa at Nasa”,回文,检查为回文。
  • “我什么都不知道”,不是回文,检查为不是回文。
  • “不是回文”,不是回文,检查为回文。

我基本上需要一些帮助来理解我的代码到底哪里出错了。谢谢!

/*
"A Santa at Nasa" is an example of palindrome.
*/

import java.util.Scanner;

public class Palindrome
{
public static void main (String[] args)
{
boolean isPalindrome = false;
Scanner kb = new Scanner(System.in);
System.out.println("Enter a string:");
String userInput = kb.nextLine();
userInput = userInput.trim().replaceAll(" ", "").toLowerCase();
char[] array = new char[userInput.length()];
char[] reverseArray = new char[userInput.length()];
int i = 0;
int j = userInput.length();

do {
i++;
j--;

array[i] = userInput.charAt(i);
reverseArray[j] = userInput.charAt(j);

if (array[i] != reverseArray[j])
{
isPalindrome = false;
}
else
{
isPalindrome = true;
}

} while (j > i);

if(isPalindrome)
{
System.out.println("It's a palindrome.");
}
else
{
System.out.println("Not a palindrome.");
}
}
}

最佳答案

一旦确定输入不是回文,就应该结束测试。

目前您的算法可以改变主意!

你也过早地增加了 i 。

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

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