【问题标题】:Trouble with recursion and text file递归和文本文件的问题
【发布时间】:2017-03-28 17:38:24
【问题描述】:

这个程序接受输入“你好,我的名字是鲍勃”,然后把它向后吐出。我真的需要帮助使程序读取文本文件并向后吐出文本文件。提前致谢!

public class Recursion
{
 public static void main(String[] args) throws FileNotFoundException {
 System.out.println(printBackwards("hello my name is bob")); 
}



public static String printBackwards(String s){
 if(s.length() <= 1)
        return s;
    else 
        return printBackwards(s.substring(1,s.length()))+s.charAt(0);
  }
}

【问题讨论】:

  • 我想这是作业,但这是一个单行解决方案(不使用递归)读取'input.txt':System.out.println(new StringBuilder(new Scanner(new File("input.txt")).useDelimiter("\\Z").next()).reverse());
  • @Hypino 如果您查看 OP 发布的代码,您应该会看到他已经实现了“反向字符串方法”。他只是问如何从/向一个读/写输入/输出文件。
  • @user6904265 哦,是的,我的错误。 How do I create a Java string from the contents of a file? 的可能重复项
  • @Hypino 好的,是的,但他还询问如何在输出文件中写入反转的字符串。

标签: java recursion text-files


【解决方案1】:

根据问题的 cmets,这将读取一个名为 input.txt 的文件,并将其保存到一个名为 output.txt 的新文件中,使用您的方法来反转 String

input.txt 中的所有行首先添加到List

List 然后从最后一个元素向后迭代,每次迭代将反向的String 写入 output.txt。

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Scanner;

public class Example {

    public static void main(String[] args) throws IOException {    
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
            Scanner scanner = new Scanner(new File("input.txt"));
            List<String> fileContents = new ArrayList<>();
            while (scanner.hasNextLine()) {
                fileContents.add(scanner.nextLine());
            }
            ListIterator<String> it = fileContents.listIterator(fileContents.size());
            while (it.hasPrevious()) {
                writer.write(printBackwards(it.previous()));
                writer.newLine();
            }
        }
    }

    public static String printBackwards(String s) {
        if (s.length() <= 1) {
            return s;
        } else {
            return printBackwards(s.substring(1, s.length())) + s.charAt(0);
        }
    }
}

如果您只想将其显示到标准输出,您可以将其调整为以下内容:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Scanner;

public class Example {

    public static void main(String[] args) throws FileNotFoundException {
        Scanner scanner = new Scanner(new File("input.txt"));
        List<String> fileContents = new ArrayList<>();
        while (scanner.hasNextLine()) {
            fileContents.add(scanner.nextLine());
        }
        ListIterator<String> it = fileContents.listIterator(fileContents.size());
        while (it.hasPrevious()) {
            System.out.println(printBackwards(it.previous()));
        }
    }

    public static String printBackwards(String s) {
        if (s.length() <= 1) {
            return s;
        } else {
            return printBackwards(s.substring(1, s.length())) + s.charAt(0);
        }
    }
}

或者正如我之前在评论中所说,您可以一口气阅读整个文件并将其反转:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Example {

    public static void main(String[] args) throws FileNotFoundException {
        System.out.println(printBackwards(new Scanner(new File("file.txt")).useDelimiter("\\Z").next()));
    }

    public static String printBackwards(String s) {
        if (s.length() <= 1) {
            return s;
        } else {
            return printBackwards(s.substring(1, s.length())) + s.charAt(0);
        }
    }
}

【讨论】:

    【解决方案2】:

    使用此代码从文本文件中获取要反转的字符串:

    try{
        String myString;
        BufferedReader input = new BufferedReader(new FileReader("Filepath.txt");
        while((myString = input.readLine()) != null){}
    }
    catch(FileNotFoundException ex){
        //Error Handler Here
    }
    catch(IOException ex){
        //Error Handler Here
    } finally {
        try{
            if(br != null) br.close();
        }
        catch(IOException ex){
            ex.printStackTrace();
        }
    }
    

    别忘了导入:

    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.FileNotFoundException
    

    【讨论】:

      【解决方案3】:

      这应该可以如您所愿。我假设在filename_in.txt 你只有一行,否则你必须循环(我让你做这个练习):

      public static void main(String[] args){
             Scanner in = null; 
             PrintWriter writer = null;
             try{
                 in = new Scanner(new FileReader("filename_in.txt"));
                 writer = new PrintWriter("filename_out.txt");
                 writer.println(printBackwards(in.nextLine()));
              } catch (Exception e) {
                 e.printStackTrace();
              }
             finally {
                 in.close(); 
                 writer.close();
             }
          }
      

      【讨论】:

      • @downvoter.. 我能问你为什么投反对票吗?谢谢!
      猜你喜欢
      • 2013-05-05
      • 2013-06-07
      • 1970-01-01
      • 1970-01-01
      • 2011-04-15
      • 1970-01-01
      • 2016-12-18
      • 2012-11-18
      • 2020-01-27
      相关资源
      最近更新 更多