Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

fBaran

macrumors regular
Original poster
Oct 22, 2003
218
0
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();
		}
	}
}
 

Blurg

Guest
May 3, 2005
49
0
Why not just do this? (assuming your words are separated by spaces)

Code:
public static void main(String args[]) {
	try {
			Scanner s = new Scanner(new File("input.txt"));
			while (true) {
				String st = s.nextLine();
				
				String[] splitString = st.split(" ");
				for (int i = 0; i < splitString.length; i++) {
					if (splitString[i].equals("print") && i != splitString.length-1) {
						System.out.println(splitString[i+1]);
					}
					else if (splitString[i].equals("end")) {
						System.exit(0);
					}
					
				}
			}
		} catch (Exception e) {
			System.out.println();
		}
	}
 

rickb

macrumors newbie
Dec 5, 2006
12
0
if (s1.equals("end")){
if (s1.equals("print")){
printIt = true;
throw new RuntimeException();
}
}

The problem is that you only get the exception if s1 equals both items which is impossible, it will either equal "end" or "print" but not both. Take out the second if statement
 

Eraserhead

macrumors G4
Nov 3, 2005
10,434
12,250
UK
if (s1.equals("end")){
if (s1.equals("print")){
printIt = true;
throw new RuntimeException();
}
}

The problem is that you only get the exception if s1 equals both items which is impossible, it will either equal "end" or "print" but not both. Take out the second if statement

If you do
Code:
if(s1.equals("end") || s1.equals("print")){
	printIt = true;
	throw new RuntimeException();
}

You should get the effect you want.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.