Re: Error with my filter program
In article
<6b1a8a88-6116-414d-99b2-e430b25d40f0@a8g2000prf.googlegroups.com>,
SamuelXiao <foolsmart2005@gmail.com> wrote:
On Sep 8, 3:29?am, Bo Vance <bowman.va...@invalid.invalid> wrote:
[preserving Bo's excellent advice]
Have you precisely defined the problem?
So, You Need to Write a Program but Don't Know How to Start
<http://home.earthlink.net/~patricia_shanahan/beginner.html>
The Java Language Specification, Third Edition
<http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html>
Specifically Chapters 2 and 3
<http://java.sun.com/docs/books/jls/third_edition/html/grammars.html>
<http://java.sun.com/docs/books/jls/third_edition/html/lexical.html>
The Java? Programming Language Compiler, javac
<http://java.sun.com/javase/6/docs/technotes/guides/javac/index.html>
I have found out the bugs and fixed the problem[...]
Excellent! Consider sharing your results.
I still don't know what is different between the following two
statement:
1. while(scanfile.hasNext())
2.while((tryread = scanfile.nextLine())!=null)
In fact, for the 1st one, the compiler will not complain but the 2nd
will. Why?
The methods scanfile.hasNext() and scanfile.nextLine() work as
advertised. The problem was that the logic in your code called substring
on the result using a negative index. This caused a predictable
IndexOutOfBoundsException, as documented in String:
<http://java.sun.com/javase/6/docs/api/java/util/Scanner.html>
<http://java.sun.com/javase/6/docs/api/java/lang/String.html>
Your more serious problem is that Scanner is designed to break "its
input into tokens using a delimiter pattern," which is an awkward fit
for your problem, absent an obvious delimiter.
An elementary approach is to start with a program that simply copies
standard input to standard output:
/**
* Copy stdin to stdout, byte by byte.
* @author John B. Matthews
*/
import java.io.*;
public class FilterStream {
public static void main(String[] args) throws IOException {
BufferedInputStream in = new BufferedInputStream(System.in);
int c;
while ((c = in.read()) != -1) {
// your filtering code goes here
System.out.write(c);
}
}
}
This is fine, but it has limitations with character encoding and line
termination. Fortunately, the platform provides a alternative:
/**
* Copy stdin to stdout, line by line.
* @author John B. Matthews
*/
import java.io.*;
public class FilterLine {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
String s;
while ((s = in.readLine()) != null) {
// your filtering code goes here
System.out.println(s);
}
}
}
Once compiled, you can invoke the filter on your test input and see your
results immediately.
$ java FilterLine < test.txt
--
John B. Matthews
trashgod at gmail dot com
home dot woh dot rr dot com slash jbmatthews