Open/Read file using recursion
Hello, I am having a tough time trying to change my code from reading a text file using a while loop, to reading a file using recursion...
This is my little test program now. It opens up input.txt and reads the input using a while loop and stringtokenizer.
Code:
import java.io.*;
import java.util.*;
class test
{
public static void main (String[] args) throws java.io.IOException
{
String filename = "input.txt";
// Initialize the reader
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(filename));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Initialize the string variable that will contain each
// line of text read from the file
String s = "";
// Read until the end of file
while (s!=null)
{
try {
s = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s != null)
{
StringTokenizer st = new StringTokenizer (s);
String test;
while (st.hasMoreTokens())
{
test = st.nextToken();
if (test.equalsIgnoreCase("q"))
{
System.out.println ("User quit.");
break;
}
if (test.equalsIgnoreCase("one"))
System.out.println ("1");
if (test.equalsIgnoreCase("two"))
System.out.println ("2");
if (test.equalsIgnoreCase("three"))
System.out.println ("3");
}
} //end if
} //end while
} //end main
} //end class
the input.txt contains
and works fine as far as I can tell. So now when making a recursive method to do this... I'll need to call the nextToken() recursively with hasMoreTokens() being the base case? Recursive code is always confusing to me...
Thanks for your time.