Java help: System.out problem

Discussion in 'Mac Programming' started by fBaran, Feb 14, 2007.

  1. macrumors regular

    Joined:
    Oct 22, 2003
    #1
    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();
    		}
    	}
    }
     
  2. Guest

    Joined:
    May 3, 2005
    #2
    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();
    		}
    	}
    
     
  3. macrumors newbie

    Joined:
    Dec 5, 2006
    #3
    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
     
  4. macrumors G4

    Eraserhead

    Joined:
    Nov 3, 2005
    Location:
    UK
    #4
    If you do
    Code:
    if(s1.equals("end") || s1.equals("print")){
    	printIt = true;
    	throw new RuntimeException();
    }
    
    You should get the effect you want.
     

Share This Page