从TXT文件中读取数字
2008-01-05 09:02:46 来源:WEB开发网核心提示:import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;import java.io.Reader;import java.io.StreamTokenizer;// The buffering makes t
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StreamTokenizer;
// The buffering makes the PRogram more than 20 times faster.
public class SumFile {
public static void main(String[] a) throws IOException {
sumfile("file.txt");
}
static void sumfile(String filename) throws IOException {
Reader r = new BufferedReader(new FileReader(filename));
StreamTokenizer stok = new StreamTokenizer(r);
stok.parseNumbers();
double sum = 0;
stok.nextToken();
while (stok.ttype != StreamTokenizer.TT_EOF) {
if (stok.ttype == StreamTokenizer.TT_NUMBER)
sum += stok.nval;
else
System.out.println("Nonnumber: " + stok.sval);
stok.nextToken();
}
System.out.println("The file sum is " + sum);
}
}
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StreamTokenizer;
// The buffering makes the PRogram more than 20 times faster.
public class SumFile {
public static void main(String[] a) throws IOException {
sumfile("file.txt");
}
static void sumfile(String filename) throws IOException {
Reader r = new BufferedReader(new FileReader(filename));
StreamTokenizer stok = new StreamTokenizer(r);
stok.parseNumbers();
double sum = 0;
stok.nextToken();
while (stok.ttype != StreamTokenizer.TT_EOF) {
if (stok.ttype == StreamTokenizer.TT_NUMBER)
sum += stok.nval;
else
System.out.println("Nonnumber: " + stok.sval);
stok.nextToken();
}
System.out.println("The file sum is " + sum);
}
}
更多精彩
赞助商链接