PDA

View Full Version : Java help: System.out problem




fBaran
Feb 14, 2007, 08:23 PM
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!


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
Feb 15, 2007, 02:44 AM
Why not just do this? (assuming your words are separated by spaces)


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
Feb 15, 2007, 12:03 PM
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
Feb 15, 2007, 01:59 PM
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 if(s1.equals("end") || s1.equals("print")){
printIt = true;
throw new RuntimeException();
}


You should get the effect you want.