Please, please help me out. I will be very grateful for any
assistance.
Cheers.
Here is the text file I'm reading:
S
A apple
A eggplant
A banana
A apple
S apple
S eggplant
S banana
R apple
S apple
HERE IS MY CODE:
import java.io.*;
import java.util.*;
public class Assignment
{
private BufferedReader reader = null;
private PrintWriter outputStream = null;
private StringTokenizer st = null;
private String nextToken;
private String line;
private int numPushPop;
private int invokeMethod;
public Assignment()
{
numPushPop = 0;
invokeMethod = 0;
}
public static void main(String[] args) throws IOException
{
Assignment as = new Assignment();
as.ReadWrite("astest.txt", "te.txt");
as.closeReaderWriter();
}
public void ReadWrite(String inputFileName, String
outputFileName)
{
try
{
reader = new BufferedReader(new FileReader
(inputFileName));
outputStream = new PrintWriter(new FileOutputStream
(outputFileName, true));
//Tokenize(reader);
line = reader.readLine();
System.out.println(line);
closeReaderWriter();
}
catch (IOException e)
{
System.out.println(" Error reading file " +
inputFileName);
System.exit(0);
}
}
public String Tokenize(BufferedReader reader)throws IOException
{
line = reader.readLine();
st = new StringTokenizer(line);
System.out.println(line);
nextToken = st.nextToken();
if (nextToken.equals("S"))
{
System.out.println(st.nextToken());
invokeMethod = stackMetric(nextToken);
}
else if (nextToken.equals("L"))
{
invokeMethod = listMetric();
}
System.out.println(nextToken);
System.out.println(nextToken);
return nextToken;
}
public int stackMetric(String nextToken)throws IOException
{
MyStack my = new MyStack();
while(line!= null)
{
while(st.hasMoreTokens())
{
nextToken = st.nextToken();
if (nextToken.equals("A"))
{
nextToken = st.nextToken();
numPushPop += my.add(nextToken);
}
else if (nextToken.equals("R"))
{
nextToken = st.nextToken();
numPushPop += my.remove
(nextToken);
}
else if (nextToken.equals("S"))
{
nextToken = st.nextToken();
numPushPop += my.search
(nextToken);
}
}
line = reader.readLine();
}
return numPushPop;
}
public int listMetric()throws IOException
{
MyStack my = new MyStack();
nextToken = st.nextToken();
while(line!= null)
{
while(st.hasMoreTokens())
{
if (nextToken.equals("A"))
{
nextToken = st.nextToken();
numPushPop += my.add(nextToken);
}
else if (nextToken.equals("R"))
{
nextToken = st.nextToken();
numPushPop += my.remove(
nextToken);
}
else if (nextToken.equals("S"))
{
nextToken = st.nextToken();
numPushPop += my.search
(nextToken);
}
}
line = reader.readLine();
}
my.printMetric((double)(numPushPop));
return numPushPop;
}
public void closeReaderWriter()
{
try
{
reader.close();
outputStream.close();
}
catch (IOException e)
{
System.out.println(" End of file reached ");
System.exit(0);
}
}
}
I'm not quite sure but you should check for more tokens before
calling nextToken():
if (st.hasMoreTokens()) {...}
HTH
Harald