java - 使用 try/catch block 捕获文件输入的异常

标签 java

我很确定我的问题存在于我的 try block 中的某个地方,但我似乎无法查明它。我正在做的是从文件中读取并检查输入。如果输入>0,我想增加goodData,如果不是,它应该为值<0抛出BPIllegalValueException,或者为非整数的值抛出InputMismatchException。我希望你们能帮忙。

编辑:教授指示:

In your program, you need two exceptions to handle two kinds of bad data. For the non-integer reading, you can use nextInt() method to read an integer from the file, if the data is not an integer, InputMismatchException will be thrown. Your program must catch this exception. To handle the negative reading, you may want to declare your own Exception class: BPIllegalValueException (you are expected to write BPIllegalValueException.java that contains the class), and threw this exception when a negative value is read. Note: your program should not terminate when a bad data is read. Therefore, you must use try/catch block to handle the bad data. Your program is expected to print out (on the screen) the number of good BP readings and the number of bad data.

我的代码如下:

import java.io.*;
import java.util.*;

public class DemoEx {

public static void main(String[] args) throws IOException
{
    FileReader fr = new FileReader("BP.txt");
    BufferedReader br = new BufferedReader(fr);
    Scanner in = new Scanner(new FileReader("BP.txt"));
    int badData = 0;
    int goodData = 0;
    int data;
    String str = "";

    while((str = br.readLine()) != null)
    {   
        try
        {
            data = in.nextInt();
            if(data>0)
                goodData++;
            else if(data<0)
                throw new BPIllegalValueException(data);
            else
                throw new InputMismatchException();
        }

        catch(InputMismatchException ex)
        {
            badData++;
        }

        catch(BPIllegalValueException ex)
        {
            badData++;
        }
    }

    System.out.println("The number of good data: " + goodData);
    System.out.println("The number of bad data: " + badData);

}

}

最佳答案

当你只想增加一个计数器时为什么会抛出异常?

看起来像你想要的,

if (data > 0) 
    goodData++ 
 else 
     badData++;

现在,在执行此操作之前,请确保数据是一个整数,如果有的话,执行 .nextInt 将会得到该整数,并且将跳过所有其他非 int 值。所以这取决于你读取数据的方式,为什么是扫描仪?为什么不使用缓冲读取器和 readLine 然后将其拆分做您喜欢的任何事情?

关于java - 使用 try/catch block 捕获文件输入的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10338760/

相关文章:

Java CSV文件解析不解析末尾的空列

java - JPA/hibernate : how to automatically update fields on entity update

java - 如何正确处理 HTTP 文件服务器上的客户端 "Connection: close"请求?

java - Google App Engine 中的批量实体删除

java - 在 Apache Tomcat WebServer 中无法访问该站点

java - API 22 与 API 23 中的 Seekbar Progress Drawable 调整大小不同

java - 如何使用Picocontainer Web?

java - Weld/CDI 的最佳调试技巧是什么?

java - 在已经扩展 ActionBarActivity 的主 Activity 中扩展一个附加类?

java - MySQL在动态项目驱动程序问题