Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/315.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.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_Recursion - Fatal编程技术网

Java 需要一些帮助来为我的回文应用程序编写递归实现吗

Java 需要一些帮助来为我的回文应用程序编写递归实现吗,java,recursion,Java,Recursion,首先,我不是像我在这里看到的其他人要求的那样,要求人们“做我的家庭作业”。我已经成功地编写了一个程序的工作迭代版本,用于确定字符串是否为回文。在确定字符串是否为回文时,将忽略空格、标点符号和特殊字符。这个版本确实有效,但当我尝试在“isAlindrome()”方法中应用递归语句时,会出现堆栈溢出错误。我知道这些错误是什么,只是在这样一个程序中应用递归方法对我来说是很难理解的(我两周前才知道)。无论如何,以下是我迄今为止编译(并运行)的代码: /**Palindrome.java:一个单应用程序

首先,我不是像我在这里看到的其他人要求的那样,要求人们“做我的家庭作业”。我已经成功地编写了一个程序的工作迭代版本,用于确定字符串是否为回文。在确定字符串是否为回文时,将忽略空格、标点符号和特殊字符。这个版本确实有效,但当我尝试在“isAlindrome()”方法中应用递归语句时,会出现堆栈溢出错误。我知道这些错误是什么,只是在这样一个程序中应用递归方法对我来说是很难理解的(我两周前才知道)。无论如何,以下是我迄今为止编译(并运行)的代码:


/**Palindrome.java:一个单应用程序类,用于确定单词还是字符串
*是否是回文。此应用程序旨在忽略之间的空格
*字符、标点符号和特殊字符,同时确定单词或
*字符串是否为回文。
* 
**/
导入java.util.Scanner;
导入java.util.StringTokenizer;
导入java.util.regex.*;
公共类回文{
静态字符串回文,str,str2,str3;
/**回文应用程序的主要方法。从
*用户,从其输入中删除空格,将其字符串输入转换为
*小写字符,然后所有非字母字符将从用户的
*最后,递归方法确定输入的字符串
*由用户生成的是回文。
* 
*@param args接受参数的字符串数组
**/
公共静态void main(字符串[]args){
扫描仪输入=新扫描仪(System.in);
while(input.hasNext()){
str=removespace(input.nextLine());
str2=str.toLowerCase();
str3=正常化(str2);
}
系统输出打印LN(isPalindrome(str3));
}
/**默认构造函数
**/
公共回文(){
}
/**isAlindrome():通过字符串输入传递的布尔方法
*并使用一个for循环、两个内部while循环和一个if-else来确定
*用户输入是否为回文。
*
*@param s要测试的字符串输入
*@return true用户输入的是回文
*@return false用户输入的不是回文
**/
公共静态布尔值isAlindrome(字符串s){
int首先,最后;
for(first=0,last=s.length()-1;first'z'){
第一++;
}
而((int)s.charAt(last)<'a'| |(int)s.charAt(last)>'z'){
最后--;
}
}
如果(第一个>最后一个| | s.charAt(第一个)!=s.charAt(最后一个)){
//返回isAlindrome(s.substring(0,s.length()-1))==false;
返回false;
}
否则{
//返回isAlindrome(s.substring(0,s.length()-1))==true;
返回true;
}
}
/**
*此方法在解析的字符串中去掉标点符号
*通过,使用Java的正则表达式(regex)和Java的
*内置方法replaceAll()。传递正则表达式
*通过replaceAll()方法删除所有非字母数字
*通过方法参数传递的字符串中的字符。
* 
*@param t删除标点符号的字符串。
*
*@return t字符串已包含所有非字母数字字符
*删除,然后返回新字符串。
*/
公共静态字符串规范化(字符串t){
t=t.replaceAll(“[^a-zA-Z0-9]”,即“);
返回t;
}
/**removeSpaces():从用户输入中删除空格的方法
*然后递减字符串长度计数,这样就不会丢失任何索引
*当它递增时。
* 
*@param s将删除其空格的字符串。
*@return temp在取出空格后返回新字符串。
**/
公共静态字符串移除空间(字符串s){
StringBuilder temp=new StringBuilder;//使用输入的字符串创建新的StringBuilder
对于(inti=0;i

现在,我已经删除了递归方法中的递归语句。如果有人能告诉我我到底做错了什么,并帮助我实施一个非常好的解决方案。我宁愿坚持使用迭代版本,因为我了解它的机制,但被要求做一个递归版本(我从去年年中休息后就开始编写Java代码,但我在递归方面是一个相对新手),这被证明是一个相当大的挑战。如果您更改了代码,并且最终使用递归版本,请解释如何、何时、为什么等进行更改。我不是在寻找一个能帮我做到这一点的人,我想学习,而且我似乎是通过例子学到了最好的东西(我去年通过分析例子和阅读实现说明获得了B级及格)。非常感谢:)

编辑:我想我现在已经把递归进行得很好了,只是逻辑让我现在很困惑。以下是isAlindrome()方法的重新编码版本:

public静态布尔值isAlindrome(字符串s){
int首先,最后;
布尔值isPalindr=true;
如果(s.length()'z'){
//第一++;
//      }
//而((int)s.charAt(last)<'a'| |(int)s.charAt(last)>'z'){
//最后--;
//      }
//  }
if(first==last | | s.charAt(first)==s.charAt(last)){
//返回isAlindrome(s.子字符串(第一个,最后一个));
返回isAlindrome(s.substring(first,last))==true;
/** Palindrome.java: A sigle application class that determines if a word or a string
  * is a palindrome or not. This application is designed to ignore spaces between
  * chars, punctuation marks and special characters while determining if the word or
  * string is a palindrome or not.
  * 
  **/

import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.regex.*;

public class Palindrome{

  static String palindrome, str, str2, str3;

  /** The main method of the Palindrome application. Takes input from the
    * user, removes spaces from their input, turns their string input into
    * lowercase and then all non letter characters are taken out of the user's
    * input. Finally the recursive method determines if the string entered in
    * by the user is a palindrome.
    * 
    * @param args Takes in a string array of arguements
    **/
  public static void main(String[] args){
    Scanner input = new Scanner(System.in);
    while(input.hasNext()){ 
      str = removeSpaces(input.nextLine());
      str2 = str.toLowerCase();
      str3 = normalise(str2);
    }
    System.out.println(isPalindrome(str3));

  }

  /** The default constructor
    **/
  public Palindrome(){
  }

  /** isPalindrome(): A boolean method that is passed through a String input
    * and uses a for loop, two inner while loops and an if-else to determine
    * whether the users input is a palindrome.
    *
    * @param s The string input to be tested
    * @return true The users input is a palindrome
    * @return false The users input isn't a palindrome
    **/
  public static boolean isPalindrome(String s){

    int first, last;

    for(first = 0, last = s.length()-1 ; first < last ; first++ , last-- ){
      while( (int)s.charAt(first) < 'a' || (int)s.charAt(first) > 'z' ){
        first++;
      }
      while( (int)s.charAt(last ) < 'a' || (int)s.charAt(last ) > 'z' ){
        last--;
      }
    }
    if( first > last || s.charAt(first) != s.charAt(last) ){
      //return isPalindrome(s.substring(0, s.length()-1)) == false;
      return false;
    }
    else{
      //return isPalindrome(s.substring(0, s.length()-1)) == true;
      return true;
    }
  }

  /**
   * This method takes out punctuation marks in the string parsed
   * through, using Java's regular expressions (regex) and Java's
   * inbuilt method replaceAll(). The regex expression is passed
   * through the replaceAll() method to remove all non alpha-numeric
   * characters from the string passed through the method's parameter.
   * 
   * @param t The string that will have punctuation stripped from it.
   *
   * @return t The string has had all non alpha-numeric characters
   * removed and the new string is then returned.
   */
  public static String normalise(String t){
    t = t.replaceAll("[^a-zA-Z0-9]", "");
    return t;
  }

  /** removeSpaces(): A method that deletes spaces from the users input
    * and then decrements the string length count so any indexes aren't missed
    * when it is incremented.
    * 
    * @param s The string which is going to have it's spaces removed.
    * @return temp The new string is then returned after the spaces have been taken out.
    **/
  public static String removeSpaces(String s){
    StringBuilder temp = new StringBuilder(s); //creates a new StringBuilder with the inputted String
    for(int i = 0; i < temp.length(); i++){ //do this for the entire length of the StringBuilder

      if(temp.charAt(i) == ' '){ //if the char at i is a space

        temp.deleteCharAt(i); //remove the char
        i--; //subtract 1 from the counter so we don't miss an index when we increment it
      }
    }
    return temp.toString(); //return the new String
  }
}
  public static boolean isPalindrome(String s){

    int first, last;
    boolean isPalindr = true;

    if (s.length() <= 1){
      return true; // Base case
    }

    for(first = 0, last = s.length()-1 ; first < last ; first++ , last-- ){
//      while( (int)s.charAt(first) < 'a' || (int)s.charAt(first) > 'z' ){
//        first++;
//      }
//      while( (int)s.charAt(last ) < 'a' || (int)s.charAt(last ) > 'z' ){
//        last--;
//      }
//  }
      if( first == last || s.charAt(first) == s.charAt(last) ){
        //return isPalindrome(s.substring(first, last));
        return isPalindrome(s.substring(first, last)) == true;
        //isPalindr = false;
      }
      else{
        return isPalindrome(s.substring(first, last)) == false;
        //isPalindr = true;
      }
    }
    return isPalindr;
  }
public static boolean isPalindrome(String s){
   for loop {
      isPalindrome(); 
   }
}
isPalindrome(1) begins execution and calls isPalidrome(2)
 isPalindrome(2) begins execution and calls isPalidrome(3)
  isPalindrome(3) begins execution and calls isPalidrome(4)
   isPalindrome(4) begins execution and calls isPalidrome(5)
    isPalindrome(5) begins execution and returns to isPalindrome(4)
   isPalindrome(4) resumes execution and returns to isPalindrome(3)
  isPalindrome(3) resumes execution and returns to isPalindrome(2)
 isPalindrome(2) resumes execution and returns to isPalindrome(1)
isPalindrome(1) resumes execution and returns.
Plate 1 is given to you.  Are there 25 plates?  No.  Add another plate.
 Plate 2 is stacked on top of Plate 1.  Are there 25 plates?  No.  Add another plate.
  Plate 3 is stacked on top of Plate 2.  Are there 25 plates?  No.  Add another plate.
   ...
    Plate 24 is stacked on top of Plate 23.  Are there 25 plates?  No.  Add another plate.
     Plate 25 is stacked on top of Plate 24.  Are there 25 plates?  Yes.  Mission Accomplished.  Now, let's put the plates back.
     Plate 25 is removed.
    Plate 24 is removed.
   ...
  Plate 3 is removed.
 Plate 2 is removed.
Plate 1 is removed.
bool stackPlates(int i){
   plateStack.addPlate();

   if (plateStack.wasDropped == true) { return false; }     // Were the plates dropped?  Return FALSE to indicate failure.
    else if (i < 25) { return stackPlates(i+1); }           // Are there 25 plates yet?  If not, add another.
     else { return true; }                                  // There are 25 plates stacked.  Return TRUE to indicate success.

   plateStack.removePlate(i);
}
bool success = stackPlates(1);

if (success==TRUE) { cout << "CONGRATULATIONS!  YOU STACKED 25 PLATES!"; }
 else { cout << "YOU BROKE THE PLATES!  BETTER LUCK NEXT TIME!"; }
bool isPalindrome(string s, int i) {

   char first = s[i];                   // REPLACE THIS WITH THE CODE TO SKIP SPACES & SPECIAL CHARACTERS
   char last = s[(s.length -1) -i];     // REPLACE THIS WITH THE CODE TO SKIP SPACES & SPECIAL CHARACTERS

   if ( first != last )  { return false; }                // return false if mismatch letter
    else if ( i >= (s.length/2) ) { return true; }        // return true if string fully checked
     else { return isPalindrome(s, i+1); }                // string not fully checked; move to next letter

}
public static boolean isPalindrome(String s) {
    if (s.length() <= 1) return true; // base case
    return s.charAt(0) == s.charAt(s.length()-1) && isPalin(s.substring(1,s.length()-1)); // recursive case
}