如果文件具有无效的值/字符,Java会抛出异常

问题描述 投票:0回答:2

我有一个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++;
    }

谢谢 :)

java file exception throw
2个回答
4
投票

hashNextInt()更改为hasNext(),您将根据要求获得例外,

while (file.hasNextInt()) {

while (file.hasNext()) {

0
投票

如果要在不抛出异常的情况下检测问题,请添加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
        }
   }

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

© www.soinside.com 2019 - 2024. All rights reserved.