如何在没有局部变量的情况下反向打印字符串,一次一个字符

时间:2014-11-10 20:05:02

标签: java string recursion char

我必须创建一个带有String的递归方法。它不能在这种方法中存储任何字符串。

public static String printBackwards(String s)
{

    if (s.length() == 0) 
    {
        return s;
    }
    else
    {
        return printBackwards(s.substring(1)) + s.charAt(0);
    }
}

这是我到目前为止所拥有的

示例I输入一个表示"的字符串您好"它返回到终端

2 个答案:

答案 0 :(得分:1)

如果我正确理解您的问题,您希望方法本身一次打印一个字符。在这种情况下,返回类型为void

public static void printBackwards(String s) {
    if (s.length() != 0) {
        printBackwards(s.substring(1));
        System.out.println(s.charAt(0));
    }
}

答案 1 :(得分:0)

这应该有效。但是,我在注释中内置了一些......轻微的错误,以防止您简单地复制和粘贴它。你最好在转入之前找到它们 - 如果没有评论,你不敢把它转过来;)

注意:这不会保留前导空格。您可能希望将其添加为练习。

import static java.lang.System.out;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;

public class Reverse {

  private static void printBackwards(String line) {

    if (line.length() == 0) {
      /* We are at the end of the line, we can continue */
      out.println();
      return;
    }
    /* We print the _last_ character of the string.
     * Remember, indices start at 0! */
    out.print(line.charAt(line.length() - 1));

    /* We reverse the part of the string we haven't printed */
    printBackwards(line.substring(0, line.length() - 1));
  }

  public static void main(String[] args) {

    /* If we don't have anything to input, no action is needed */
    if(args.length > 0) {

      /* Kind of a bonus: Any number of files can be processed */
      for(int a = 0; a<= args.length-1; a++){

        /* We need to construct a Path, since BufferedReader requires one */
        Path path = FileSystems.getDefault().getPath(args[a]);

        /* We do not initialize, as we want line to be null if the line.read() fails */
        String line;

        try {

          /* We construct a BufferedReader, which is pretty fast even for large text files */
          BufferedReader reader = Files.newBufferedReader(path, Charset.forName("UTF-8"));

          /* Next, we read each line... */
          while ((line = reader.readLine()) != null ) {
            /* ... and have it reversed */
            printBackwards(line);
          }
        } catch (IOException ex) {
          out.print("Something went wrong during line read or during creation of BufferedReader");
          ex.printStackTrace();
        }
      }
    }
  }
}