Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 检查字符串是否为回文_Java_Boolean_Palindrome - Fatal编程技术网

Java 检查字符串是否为回文

Java 检查字符串是否为回文,java,boolean,palindrome,Java,Boolean,Palindrome,我假设使用布尔值来检查字符串是否为回文。我犯了一个错误,不知道我做错了什么。我的程序之前已经有3个由用户输入的字符串。谢谢,我也在使用java public boolean isPalindrome(String word1, String word2, String word3){ int word1Length = word1.length(); int word2Length = word2.length(); int word3Length = word3.length();

我假设使用布尔值来检查字符串是否为回文。我犯了一个错误,不知道我做错了什么。我的程序之前已经有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(字符串word1、字符串word2、字符串word3){
int-word1Length=word1.length();
int-word2Length=word2.length();
int-word3Length=word3.length();
for(int i=0;i
您可以这样做:

首先构建一个新字符串,然后检查它是否相等

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个方法
public boolean isPalindrome(字符串字)
。摆脱您的方法
isAlindrome(String,String,String)
。确保你的方法在一个类中,而不是另一个方法。我看到他们只使用了1个字符串,但我的程序有3个?不知道该做什么来防止堆栈溢出!您可以通过格式化代码以提高可读性和消除滚动来改进问题。你甚至可能会发现自己的问题。这是可行的,但我很困惑为什么它只需要1个字符串?这只是因为算法,你不需要你的函数来输入3个参数,如果你想检查3个字符串,只需使用不同的参数调用此函数3次。它“接收”只有一个parSorry,你可以从这里开始: