java - Palindrome with even numbers
问题描述
I've been working on a palindrome and it won't support an even number of words. I'm not the best at coding. It supports words like "racecar" or "tacocat", but it won't let me use a word/name like "Hannah". I'm new at this coding stuff so anything would really be appreciated.
import java.util.Scanner;
public class Palindrome
{
public static void main(String args [])
{
System.out.printf("\f");
Scanner input = new Scanner(System.in);
System.out.println("enter a word");
String word = input.nextLine();
int size = word.length();
int correct = 0;
int incorrect = 0;
for (int count = 1; count < size; count++)
{
int start = (word.charAt(count));//starting
int end = (word.charAt(size-count));//ending
if (start == end)
correct++;
else
incorrect++;
}
if (correct == 0)
System.out.printf("%s is a palindrome", word);
else
System.out.printf("%s is not a palindrome", word);
}
}
解决方案
你的代码有很多问题:
您正在比较错误索引的字符。例如,您将第二个字符(其索引为 1)与最后一个字符(其索引为 size - 1)进行比较。
count
应该初始化为0
,并且end
应该是word.charAt(size-count-1)
。您报告字符串何时是回文
correct == 0
,何时应该是incorrect == 0
(顺便说一句,您不需要计数器,只需一个布尔值)。如果您希望检查不区分大小写,可以在运行循环之前将字符串转换为小写。
这应该有效:
public static void main(String args [])
{
System.out.printf("\f");
Scanner input = new Scanner(System.in);
System.out.println("enter a word");
String word = input.nextLine().toLowerCase();
int size = word.length();
boolean isPalindrome = true;
for (int count = 0; count < size; count++)
{
int start = (word.charAt(count));//starting
int end = (word.charAt(size-count-1));//ending
if (start != end) {
isPalindrome = false;
break;
}
}
if (isPalindrome)
System.out.printf("%s is a palindrome", word);
else
System.out.printf("%s is not a palindrome", word);
}
推荐阅读
- nginx - 如何使用“controller.nodeSelector”选项将 nginx-ingress 控制器部署到 Kubernetes 主节点?
- css - 如何在引导程序 4.5 中从移动设备上的行中删除填充?
- visual-studio-code - 如何阻止对象在 fira 代码 iScript 中显示为草书?
- vb.net - 尝试在数据集列表达式中使用 DateDiff 函数
- ruby - Heroku:将 Ruby 应用程序从 Cedar-14 升级到 Heroku-18
- java - 如何在 AfterTestCase Katalon 中使用 Java 指令导出 Fiddler 会话
- javascript - 带有 Javascript 选项的下拉列表 HTML 必需元素
- symfony - Symfony 5 - 下载使用 vich 上传的文件
- c# - Xamarin 图像控件未设置图像源
- django - Django 我可以在模型中放置多少个字段?