从TXT文件中一行一行读取数字
2008-01-05 09:02:44 来源:WEB开发网核心提示:import java.io.FileReader;import java.io.IOException;import java.io.LineNumberReader;import java.io.StreamTokenizer;public class SumLine {public static void mai
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.StreamTokenizer;
public class SumLine {
public static void main(String[] a)throws IOException {
sumLines("file.txt");
}
static void sumLines(String filename) throws IOException {
LineNumberReader lnr = new LineNumberReader(new FileReader(filename));
lnr.setLineNumber(1);
StreamTokenizer stok = new StreamTokenizer(lnr);
stok.parseNumbers();
stok.eolIsSignificant(true);
stok.nextToken();
while (stok.ttype != StreamTokenizer.TT_EOF) {
int lineno = lnr.getLineNumber();
double sum = 0;
while (stok.ttype != StreamTokenizer.TT_EOL) {
if (stok.ttype == StreamTokenizer.TT_NUMBER)
sum += stok.nval;
stok.nextToken();
}
System.out.PRintln("Sum of line " + lineno + " is " + sum);
stok.nextToken();
}
}
}
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.StreamTokenizer;
public class SumLine {
public static void main(String[] a)throws IOException {
sumLines("file.txt");
}
static void sumLines(String filename) throws IOException {
LineNumberReader lnr = new LineNumberReader(new FileReader(filename));
lnr.setLineNumber(1);
StreamTokenizer stok = new StreamTokenizer(lnr);
stok.parseNumbers();
stok.eolIsSignificant(true);
stok.nextToken();
while (stok.ttype != StreamTokenizer.TT_EOF) {
int lineno = lnr.getLineNumber();
double sum = 0;
while (stok.ttype != StreamTokenizer.TT_EOL) {
if (stok.ttype == StreamTokenizer.TT_NUMBER)
sum += stok.nval;
stok.nextToken();
}
System.out.PRintln("Sum of line " + lineno + " is " + sum);
stok.nextToken();
}
}
}
赞助商链接