循环进行字符串输入和反转

时间:2014-02-12 18:38:30

标签: java loops reverse do-while palindrome

我正在尝试接收一个字符串,剪切第一个字母,将其放在字符串的末尾,并将其与原始输入进行比较。对某些词来说,它有效,有些则没有。我不确定这是循环的问题还是什么?

import java.util.*;
    public class Palin{

        public static void main(String args[])
        {
          String original,input;
          Scanner sc=new Scanner(System.in);

          System.out.println("Enter word and I will tell you if it has the property of a palindrome: ");
          original = sc.nextLine();
          char firstLetter = original.charAt(0);
          input = original.substring(1);
          input = input + firstLetter;
          StringBuilder input2=new StringBuilder(input).reverse();
          String s2=new String(input2);

          do{

            if(original.equals(s2))
                System.out.println(original + " is a Palindrome");
            else
                System.out.println(original + " is not a Palindrome");
                System.out.println("Enter another word. Or enter \"quit\" to end");
                original = sc.nextLine();
            } while (!(original.equalsIgnoreCase("quit")));

       }

}

2 个答案:

答案 0 :(得分:0)

如果您只想检查String是否是回文,您可以尝试类似:

    System.out.println("Enter String");
    Scanner s = new Scanner(System.in);
    String str = s.nextLine();
    StringBuilder sb = new StringBuilder(str);
    String rev = sb.reverse().toString();
    System.out.println(rev);
    if(str.equals(rev)){
        System.out.println("equal");
    }else{
        System.out.println("not equal");
    }

表示字符串的区分大小写使用String API。

答案 1 :(得分:0)

我想我只需要清理do-while的引用和位置。谢谢你的帮助。!

输出

输入单词,我会告诉你它是否具有回文属性: 回文 Palindrome没有Palindrome财产 输入另一个单词。或输入“退出”结束 不均匀的 不均匀有Palindrome属性 输入另一个单词。或输入“退出”结束 香蕉 香蕉有Palindrome属性 输入另一个单词。或输入“退出”结束 梳妆台 梳妆台有Palindrome房产 输入另一个单词。或输入“退出”结束 退出

以下修订的代码。

import java.util。*;         公共阶层佩林{

        public static void main(String args[])
        {
          String original,input;
          Scanner sc=new Scanner(System.in);

          System.out.println("Enter word and I will tell you if it has the property of a      palindrome: ");
          original = sc.nextLine();

        do{

          char firstLetter = original.charAt(0);
          input = original.substring(1);
          input = input + firstLetter;

          StringBuilder input2=new StringBuilder(input).reverse();
          String s2=new String(input2);



            if(original.equals(s2))
                System.out.println(original + " has a Palindrome property");
            else
                System.out.println(original + " does not have a Palindrome property");
                System.out.println("Enter another word. Or enter \"quit\" to end");
                original = sc.nextLine();
            } while (!(original.equalsIgnoreCase("quit")));

       }

}