The purpose of this code is to read from a file "input.txt" and everytime it see the word "print" it will print to console the word that follows it. If it sees the word "end" it should exit. Here's what I have so far, but it doesn't do it properly. It prints everything after it sees "print". Please help, thanks!
Code:
import java.io.*;
import java.util.*;
public class A6325 {
public static void main(String args[]) {
try {
Scanner s = new Scanner(new File("input.txt"));
while (true) {
String st = s.nextLine();
StringTokenizer t = new StringTokenizer(st," _.,-");
boolean printIt = false;
while (t.hasMoreTokens()) {
String s1 = t.nextToken();
if (s1.equals("print"))
printIt = true;
if (s1.equals("end")){
if (s1.equals("print")){
printIt = true;
throw new RuntimeException();
}
}
}
Scanner sc = new Scanner(st).useDelimiter("//s*print //s*");
String printThis = sc.next();
String print = "print ";
int pIndex = printThis.indexOf(print) + 5;
printThis = printThis.substring(pIndex);
if (printIt)
System.out.println(printThis);
}
} catch (Exception e) {
System.out.println();
}
}
}