【发布时间】:2011-06-04 09:15:37
【问题描述】:
我使用扫描仪将文本文件读入 java 程序。我现在想计算文件中所有整数值的总和。文件结构简单。
Nottinghill_Gate,120
High_Street_Kensignton,100
Gloucester_Road,50
South_Kensignton,200
Sloane_Square,100
Victoria,300
St_James_Park,200
Westminster,100
Embankment,200
Temple,150
Blackfriars,200
Mansion_House,300
Cannon_Street,190
Monument,200
Tower_Hill,160
Aldgate,190
Liverpoool_Street,60
Moorgate,50
Barbican,120
Farrington,130
Kings_Cross_St_Pancras,150
Euston_Square,180
Great_Portland_Street,120
Baker_Street,135
Edware_Road,112
Paddington,115
Bayswater,165
我的代码是
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class DataScanner {
public static void readFile(String fileName) {
try {
Scanner scanner =
new Scanner(new File(fileName));
scanner.useDelimiter
(System.getProperty("line.separator"));
while (scanner.hasNext()) {
parseLine(scanner.next());
//int total =+ distance;
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void parseLine(String line) {
Scanner lineScanner = new Scanner(line);
lineScanner.useDelimiter("\\s*,\\s*");
String current = lineScanner.next();
int distance = lineScanner.nextInt();
System.out.println("The current station is " + current + " and the destination to the next station is " + distance + ".");
int total =+ distance;
System.out.println("The total distance is " + total);
}
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("usage: java TextScanner2"
+ "file location");
System.exit(0);
}
readFile(args[0]);
}}
我知道我必须改变
int distance = lineScanner.nextInt();
System.out.println("The current station is " + current + " and the destination to the next station is " + distance + ".");
int total =+ distance;
System.out.println("The total distance is " + total);
但我不太确定该怎么做。你能帮我吗?
【问题讨论】: