【问题标题】:Java throw an exception if file has an invalid value/character如果文件具有无效的值/字符,Java 会抛出异常
【发布时间】:2017-12-22 00:27:03
【问题描述】:

我有一个 txt,我想扫描它,每次读取一个整数时,我都想将它输入到我已经创建的数组中。

当它读取除 int 以外的内容(例如 String、double 甚至是空行)时,如何抛出异常?

这就是我读取文件并完成数组的方式:

    file= new Scanner(new File(file_name));

    int[] txt = new int[cnt]; // cnt , the number of lines in my txt

    while ( file.hasNextInt()) {
        txt[count] = file.nextInt(); 
        count++;
    }

谢谢你:)

【问题讨论】:

  • 阅读 javadocs - 如果您想处理其他内容,请不要使用 nextInthasNextInt

标签: java file exception throw


【解决方案1】:

hashNextInt() 更改为hasNext(),您将收到请求的异常,

while (file.hasNextInt()) {

while (file.hasNext()) {

【讨论】:

    【解决方案2】:

    添加到 Elliott 的答案中,如果您想检测问题而不抛出异常:

       while (file.hasNext()) {
            if (file.hasNextInt()) {
                txt[count] = file.nextInt(); 
                count++;
            } else {
                System.error.println(file.next() + " is not an int"); // also skips bad data
            }
       }
    

    (提示:阅读并尝试理解逻辑......)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-03
      • 1970-01-01
      • 2014-02-23
      • 2013-02-13
      • 1970-01-01
      • 2014-11-12
      • 1970-01-01
      • 2016-11-07
      相关资源
      最近更新 更多