作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在学习 Java。我正在构建这个回文识别器并使用两个带有字符的数组,我认为我用我发现的其他东西得到了很好的实现,但我正在绞尽脑汁地理解为什么它到目前为止没有按预期工作。发生了什么:
我基本上需要一些帮助来理解我的代码到底哪里出错了。谢谢!
/*
"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/
我想开发一个 Skype 机器人,它将用户名作为输入,并根据用户输入以相反的字符大小写表示hello username。简而言之,如果用户输入他的名字 james,我的机器人会回复他为 Hello J
我是一名优秀的程序员,十分优秀!