-4

我正在尝试从文件中读取一堆数字并将它们相加。但我也在文件中添加了一些字符串。我现在正在尝试读取数字将它们加在一起并使用 try/catch 块我试图在文件读取字符串而不是整数时显示错误。但是,一旦代码从文件中读取一个字符串,它就会给我错误,代码不会继续将数字相加。它只是打印错误并打印 0。如何修改它以便它继续读取数字并将它们相加并在读取字符串后显示错误消息。

代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
import java.util.Scanner;
public class AddNumbers {

public static void main (String[]args) {
    try{
        File myFile = new File("numbers.txt");
        Scanner scan = new Scanner(myFile);

        int x;
        int y = 0;
        try{
            //Read file while it has a line 
            while(scan.hasNextLine()){
            //scan a integer value
                x = scan.nextInt();
            //Add the scanned value to y
                y = y+x;
            }
        }catch(InputMismatchException e){
            //If a string is found then print this error
            System.err.println("Strings found! Error!");
        }
        System.out.println(y);
        scan.close();

    }catch(FileNotFoundException e){
        System.err.println("No such file exists!");
        System.out.println();
    }


}

}

文件内容

Albert 
10000
20000
30000
Ben 
50000
12000
Charlie 
4

3 回答 3

1

首先,将try-catch块放置在while循环之外。如果发生异常,控制到达catch打印错误消息的块,然后退出循环。您需要将try-catch内部循环。

其次,当Scanner#nextInt()抛出异常时,Scanner不会消耗输入,在读取无效整数的情况下导致无限循环。您可以简单地使用读取整行Scanner#nextLine()并将其解析为int

while (scan.hasNextLine()) {
    try {
        // scan a integer value
        String line = scan.nextLine();
        x = Integer.parseInt(line);
        // Add the scanned value to y
        y = y + x;
    } catch (NumberFormatException e) { // this can be thrown by Integer.parseInt(line)
        // If a string is found then print this error
        System.err.println("Strings found! Error!");
    }
}
于 2015-07-29T19:01:21.053 回答
0

尝试将该行作为字符串读取,然后Integer.parseInt(x)在抛出异常时使用并捕获它。

有关信息,请参见此处Integer.parseInt()

于 2015-07-29T19:01:03.200 回答
0

您需要将 try/catch 放在 while 循环中。

While(scan.hasNextLine()){
    try{
      x=scan.nextInt();
      // add
    }catch(InputMismatchException ime){
       //write error
    }
}
于 2015-07-29T19:04:47.650 回答