【问题标题】:check the Strings if they are palindrome检查字符串是否是回文
【发布时间】:2016-11-28 23:24:50
【问题描述】:

我想使用布尔值来检查字符串是否是回文。我收到一个错误,不知道我做错了什么。我的程序已经有 3 个先前由用户估算的字符串。谢谢,我也在用java

 public  boolean isPalindrome(String word1, String word2, String word3){

 int word1Length = word1.length();
 int word2Length = word2.length();
 int word3Length = word3.length();

 for (int i = 0; i < word1Length / 2; i++)
{
    if (word1.charAt(i) != word1.charAt(word1Length – 1 – i))
    {
        return false;
 }
}
return isPalindrome(word1);
}

for (int i = 0; i < word2Length / 2; i++)
{
if (word2.charAt(i) != word2.charAt(word2Length – 1 – i))
    {
        return false;
    }
 }
 return isPalindrome(word2);
}
 for (int i = 0; i < word3Length / 2; i++)
{
if (word3.charAt(i) != word3.charAt(word3Length – 1 – i))
{
return false;
}
}
return isPalindrome(word3);
}

  // my output should be this
 if (isPalindrome(word1)) {
  System.out.println(word1 + " is a palindrome!");
  }
  if (isPalindrome(word2)) {
  System.out.println(word2 + " is a palindrome!");
   }
  if (isPalindrome(word3)) {
  System.out.println(word3 + " is a palindrome!");
  }

【问题讨论】:

  • 你有所有的部分,你只是有一些语法错误我确定。只需使用以下签名 public boolean isPalindrome(String word) 创建 1 个方法。摆脱你的方法isPalindrome(String, String, String)。确保您的方法在一个类中,而不是在另一个方法中。
  • 我看到他们只使用了 1 个字符串,但我的程序有 3 个?不知道该怎么办
  • 欢迎来到 Stack Overflow!您可以通过格式化代码以提高可读性和消除滚动来改进您的问题。您甚至可能会发现自己的问题。

标签: java boolean palindrome


【解决方案1】:

你可以为它做一个这样的方法:

首先你建立一个新的字符串,然后检查它是否相等。

private static boolean test(String word) {
    String newWord = new String();      
    //first build a new String reversed from original
    for (int i = word.length() -1; i >= 0; i--) {           
        newWord += word.charAt(i);
    }       
    //check if it is equal and return
    if(word.equals(newWord))
        return true;        
    return false;       
}

//You can call it several times
test("malam"); //sure it's true
test("hello"); //sure it's false
test("bob"); //sure its true

【讨论】:

  • 这行得通,但我很困惑为什么它只需要 1 个字符串?
  • 只是因为算法,你不需要你的函数输入3个参数,如果你想检查3个字符串,只需用不同的参数调用这个函数3次
  • 它只“收到”一个标准杆
  • 对不起,你可以从这里开始:docs.oracle.com/javase/tutorial/java/javaOO/methods.html
猜你喜欢
  • 2012-04-05
  • 2015-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多