Java递归坏了:向后写一个句子



我需要从文件中提取一个句子,向后写,然后输出到文件中。我已经用fromFile方法很容易地提取了句子,并且用toFile方法输出句子不会有问题。

我目前的问题是递归。下面是我想要的一个例子:

原话:;这将被向后写";

新句:;向后写的是will This";

一个简单的解决方案是使用数组,但我不能这样做。我知道递归是如何工作的,但我似乎无法逐字逐句地输出句子,所以我认为我有逻辑问题。我花了几个小时寻找它,然后在网上寻找例子。我不知道该怎么办。任何帮助都非常感谢!非常感谢。

import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.*;
public class Recursion {
public static void main (String[] args) 
{
String output; //output to the second file
System.out.println("Starting program...");
System.out.println("nFirst Line:");
fromFile();

}//end Main
public static void writeBackward(String s)
{
String output; //holds the output
String newString; //holds the new string
if (s.length() < 1) //base case - no more characters in string
{
System.out.println();
System.out.println("Base Case is executed. Done.");
}
else
{
output = s.substring(0, s.indexOf(" "));
output.trim();
newString = s.substring(output.length());
System.out.print(output + " ");
writeBackward(newString);
}
}//end writeBackward
public void toFile(String output)
{
try
{
String outPutFile = "input.txt";                //file name
FileWriter fileWrite = new FileWriter(outPutFile);
BufferedWriter buffWrite = new BufferedWriter (fileWrite);
PrintWriter outFile = new PrintWriter (buffWrite);
String outLine = output;
outFile.print(outLine);
outFile.println();
outLine = "";
//flush and close the output file
buffWrite.flush ();
buffWrite.close ();
}//end try
catch(IOException exception)
{
System.out.println(exception.getMessage());
}//end catch
}//end toFile
public static void fromFile()
{
try
{
String temp; //temporary string to be sent to recursion
String inPutFile = "input.txt"; //file name
String line = "";               //line of data read from file
StringTokenizer inLine;            //tokenized string
//open the input stream
FileReader fRead = new FileReader(inPutFile);
//buffer input stream one line at a time
BufferedReader bRead = new BufferedReader (fRead);
//Get data from file
//read in the first line of the file
line = bRead.readLine();
while(line != null)
{
//parse the new line using the comma as the delimiter
temp = line;
System.out.println("Debug temp: " + temp + "Debug line: " + line);
writeBackward(temp);
//get the next line in the external file
line = bRead.readLine();
}//end while line not null
//close the input file
bRead.close ();
}//end try
catch(IOException exception)
{
System.out.println(exception.getMessage());
}//end catch
}//end fromFile
}//end RecursionClass

试试这个:

public static void writeBackward(String s) {
String output = ""; // holds the output
if (s.split(" ").length <= 1) // base case - no more characters in string
{
output += s;
System.out.print(output + " ");
System.out.println();
System.out.println("Base Case is executed. Done.");
} else {
output = s.substring(s.lastIndexOf(" ") + 1);
s = s.substring(0, s.lastIndexOf(" "));
output.trim();
System.out.print(output + " ");
writeBackward(s);
}
}

最新更新