有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java回文程序(我走上正轨了吗)?

我只有6个月的Java经验(我也是这里的新手),所以如果我的代码看起来不完全正确,请容忍我。请注意,这仍然是一项正在进行的工作。我正在尝试编写一个程序,它接受字符串并只打印回文

我应该: -创建一个名为isAlindrome的方法,该方法具有字符串参数和 -根据字符串是否为回文返回布尔值。然后 -修改main方法以使用isPalindrome仅打印回文

例如,如果我键入:“madam James apple mom timer”,它应该打印“madam”和“mom”

这基本上就是我要写的程序: 让我们用“夫人”这个词吧。程序将检查第一个字母和最后一个字母是否匹配(“madam”)。如果这是真的,那么它将检查接下来的字母,这次是“a”和“a”(“madam”),依此类推

这是我到目前为止的Java代码:

public class Palindrome 
{
    private String theWord; //Error: The value of the field Palindrome.theWord is not used

    public boolean isPalindrome( String theWord ) {
        int firstPointer = 0;
        int secondPointer = theWord.length() - 1;

        for ( int i = 0; i < theWord.length( ); i++ ) {
            if ( theWord.charAt[0] == theWord.charAt (theWord.length() - 1) ) { //Error: charAt cannot be resolved or is not a field
                return true;
            }
            return false;
        }
    }


    public static void main( String[] theWord ) {
        Palindrome = new Palindrome( ); //Error: Palindrome cannot be resolved to a variable

        for ( int i = 0; i < theWord.length; i++ ) {
            while (firstPointer < secondPointer) { //Error: "firstPointer" cannot be resolved to a variable. "secondPointer" cannot be resolved to a variable
                if ( theWord.charAt[0] == theWord.charAt (theWord.length() - 1) ) {  //Error: charAt cannot be resolved to a variable or is not a field. Cannot invoke length() on the array type String[]
                    firstPointer++; //Error: "firstPointer" cannot be resolved to a variable
                    secondPointer++; //Error: "secondPointer" cannot be resolved to a variable
                }
                System.out.println(theWord);
            }
        }
    }
}

如果你能帮我知道我哪里出了问题,我将不胜感激。请不要只给我正确的代码。我想弄明白。多谢各位

**编辑:我现在已将错误作为注释包含在代码中。顺便说一下,我正在使用Eclipse


——>**编辑2:好的,伙计们。到目前为止,我已经阅读了您的大部分答案,并且能够更正大部分代码(非常感谢大家)。我现在唯一有问题的部分是这一部分:

if ( theWord.charAt(i) == theWord.charAt (theWord.length() - i - 1) ) {
                    leftPointer++;
                    rightPointer--;

我现在得到一个“无法调用数组类型字符串[]上的字符(int)”“无法对数组类型字符串[]调用length()”。 这是剩下的两个错误,然后我将测试代码。我已经尝试解决这些问题一段时间了,但我仍然不能完全确定这些错误意味着什么

Eclipse建议我改变这个词。字符(i)到这个词。长度这不是我想要的。它还建议我从长度中删除“()”,但我认为这也不对


共 (4) 个答案

  1. # 1 楼答案

    在循环中,通过以下方式进行检查:

    boolean isPalin = true;
    for ( int i = 0; i < theWord.length( )/2; i++ ) { // loop goes till half since no need to check after that
         if ( !(theWord.charAt(i) == theWord.charAt (theWord.length() - 1 - i)) ) { // will check each letter with each end letter
             isPalin = false;
             break;
         }
    }
    return isPalin;
    

    还有一点需要补充:

    1-firstPointer-secondPointer是isAlindrome的局部变量

    2-当你将单词标记为全局变量时,似乎不需要传递它。您可以在同一个类中使用它

    3-main中的单词(String[]theWord)要求您提供作为参数的输入,最好在运行时使用控制台输入

    4-大体上,你应该拆分每个单词并将其传递给isPalindrome。在您的代码中,您没有调用isPalindrome来检查任何地方

  2. # 2 楼答案

    好吧,让我们把所有的东西都分解成一小块一小块的

    1. 输入字符串
    2. 解析字符串,检查它是否是回文
    3. 打印出字符串中的回文单词

      public class Main {
      
      public static void main(String[] args) {
      
          Scanner scan = new Scanner(System.in);
          System.out.println("Enter a sentence: ");
      
          String sentence = scan.nextLine(); // 1.
      
          String[] words = sentence.split(" ");
      
          for (String word : words) {  // 3.
              if (isPalindrome(word)) {
                  System.out.println(word);
              }
          }
      }
      
      /**
       * Check if the string is a palindrome.
       * @param string
       * @return True if string is palindrome.
       */
      public static boolean isPalindrome(String string) { // 2.
      
          for (int i = 0; i < string.length() / 2; i++) {
              if (string.charAt(i) != string.charAt(string.length() - i - 1)) {
                  return false;
              }
          }
      
          return true;
      }}
      

    一些解释

    方法/函数isAlindrome是静态的,因为我们是从静态上下文调用它的,而静态上下文是主函数。如果您想非静态地使用它,您可以将它放在一个类中,并从该类创建一个对象。其余的应该是可以理解的。:-)

  3. # 3 楼答案

    一种较好的isPalindrome方法

    最短的路径可能只是遵循以下定义: 如果你颠倒字符串,它仍然是一样的,那么它是一个回文:

    public static boolean isPalindrome(String input)
    {
        String reverse = new StringBuilder(input).reverse().toString();
        return input.equalsIgnoreCase(reverse);
    }
    

    但是如果有一个教育目标(?),并且应该出于某种原因使用迭代器,因此,从字符串的外部向内部进行迭代更有意义

    public static boolean isPalindrome(String input)
    {
      int length = input.length();
      for (int i = 0; i < length/2 ; i++)
      {
        if (input.charAt(i) != (input.charAt(length-1-i))) return false;
      }
      return true;
    }
    

    短语分析

    在您的示例中,您使用了主String[]参数的输入。这里只是一些信息,以防您想要手动将其拆分为单词

    相当于您现在得到的:

    String[] words = phrase.split("\\s+");
    for (String word : words) 
    {
      // do stuff
    }
    

    split方法使用分隔符将String拆分为String[]。分隔符\\s是一个正则表达式,它表示所有类型的空格(不仅是空格,还包括制表符、新行字符等…)

    但它并不完美(你的方式也不完美),短语中仍然可以有逗号、点和其他标记。您可以使用Character.isLetterOrDigit方法在迭代中过滤这些字符。或者,您可以只执行replace(...)来删除逗号、点和其他标记。或者也可以使用更复杂的正则表达式

    关于你的代码

    第一条错误消息:“未使用字段值”。 错误消息是由全局专用字段theWord引起的,因为它从未被使用过。没有使用它,因为在方法isPalindrom(String theWord)中还有一个同名的参数。每当您在该方法中引用theWord时,在考虑全局变量之前,它总是会优先考虑方法参数

    看起来你被设计矛盾困在这里了。 类Palindrome到底是什么?有两种选择:

    1. 它应该是像Math类那样的工具箱吗?像boolean value = Palindrome.isPalindrome("madam");
    2. 或者它应该是您使用构造函数实例化的对象?像boolean value = new Palindrome("madam").isPalindrome();

    选项1:工具箱:

    public class Palindrome 
    {
      // removed the private field theWord
    
      // make this method static !!
      public static boolean isPalindrome( String theWord ) {
        ...
      }
    
      public static void main( String[] theWord ) {
        // remove the Palindrome object
    
        // inside the loop check use the static method 
        // which does not require an object.
        if ( Palindrome.isPalindrome(word))
        {
        }
      }
    }
    

    选项2:对象

    public class Palindrome 
    {
      // keep the private field theWord
      private String theWord;
    
      public Palindrome(String theWord)
      {
        // set the value of the argument to the private field
        this.theWord = theWord;
      }
    
      // don't make this method static 
      // also you don't need the parameter any more.
      // it will now use the global field theWord instead of a parameter.
      public boolean isPalindrome() {
        ...
      }
    
    public static void main( String[] theWord ) {
        // inside the loop check use an object
        Palindrome palindrome = new Palindrome(word);
        if ( palindrome.isPalindrome())
        {
        }
    }
    

    至于第一个指针和第二个指针的错误。您需要定义和初始化这些变量。也就是说,把int firstPointer = 0;放在循环之前

  4. # 4 楼答案

    查看您的isPalindrome方法:

    if ( theWord.charAt(0) == theWord.charAt (theWord.length() - 1) 
    

    在这里,您总是将第一个字符与最后一个字符进行比较。在每次迭代中,您应该比较一对不同的字符,直到找到一对不匹配的字符,或者到达单词的中间

    您应该使用循环的i变量:

    if ( theWord.charAt(i) == theWord.charAt (theWord.length() - i - 1) 
    

    返回值应该正好相反。如果发现一对字符不匹配,则返回false。只有循环结束时不返回false,才返回true