我有一个文本文件,其中包含一些帐户持有人和他们借出的书籍数量。我需要阅读文件,添加帐户数量并添加书籍总数。
这些是账户持有人和账簿总数。
蒂姆·牛顿14Leon Jones 21
比尔鲍勃94莎拉古丁67
{
private int count;
private File inFile, outFile;
private Scanner input;
private String name;
private PrintWriter output;
private int total;
public test(String name, String id, String inFileName, String outFileName) {
inFile = new File(inFileName);
if (!inFile.exists()) {
throw new IllegalStateException(inFileName + " does not exist");
}
outFile = new File(outFileName);
}
public void makeLink() throws FileNotFoundException {
input = new Scanner(inFile);
output = new PrintWriter(outFile);
}
public void processFiles() {
try {
while (input.hasNext()) {
String line = input.nextLine();
output.println(line);
}
} catch (NullPointerException e) {
System.out.println(" Scanner not assigned");
}
}
public void closeLink() {
try {
input.close();
} catch (NullPointerException e) {
System.out.println(" Scanner not assigned");
}
try {
output.close();
} catch (NullPointerException e) {
System.out.println(" PrintWriter not assigned");
}
}
}
以下是已实施扫描仪答案的已编辑代码:
public void makeLink() throws FileNotFoundException {
input = new Scanner(inFile);
output = new PrintWriter(outFile);
numbers = new Scanner(inFile)
}
public void processFiles() {
try {
// your current code then
while (account.hasNextInt()) {
String line = input.nextLine()
while (numbers.hasNextInt()) {
total += numbers.nextInt();
}
output.println(line);
}
} catch (NullPointerException e) {
System.out.println(" Scanner not assigned");
}
}
enter code here
答案 0 :(得分:1)
使用scanner.hasNextInt()
和scanner.nextInt()
您可能想要另一台扫描程序在文件中查找数字:
private Scanner account; // initialise this in makeLink
public void processFiles() {
try {
// your current code then
while (account.hasNextInt()) {
total += account.nextInt();
}
} catch (NullPointerException e) {
System.out.println(" Scanner not assigned");
}
}
注意:阅读java API是值得的。