首页 > 解决方案 > 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);
    } 
}

标签: javapalindrome

解决方案


你的代码有很多问题:

  1. 您正在比较错误索引的字符。例如,您将第二个字符(其索引为 1)与最后一个字符(其索引为 size - 1)进行比较。count应该初始化为0,并且end应该是word.charAt(size-count-1)

  2. 您报告字符串何时是回文correct == 0,何时应该是incorrect == 0(顺便说一句,您不需要计数器,只需一个布尔值)。

  3. 如果您希望检查不区分大小写,可以在运行循环之前将字符串转换为小写。

这应该有效:

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);
} 

推荐阅读