【问题标题】:Getting an input mismatch error when trying to read an integer from a file and store it in a variable尝试从文件中读取整数并将其存储在变量中时出现输入不匹配错误
【发布时间】:2020-10-20 21:43:49
【问题描述】:
public static Matrix read(String filename) {
        
            Scanner scan = new Scanner(filename);
            int row = scan.nextInt();
            int column = scan.nextInt();
            
            Matrix mat = new Matrix(row, column);
            
            scan.nextLine();
            
            for(int i=0; i<row; i++) {
                for(int j=0; j<column; j++) {
                    mat.setElement(i, j, scan.nextInt());
                }
                scan.nextLine();
            }
            
            scan.close();
            
            return mat;
        
    }

这是我目前读取文本文件的方法。每个文本文件的顶部都有矩阵尺寸,然后是下面的矩阵行。例如:

2 3
1 1 1
2 2 2

当我尝试将第一行中的前 2 个数字存储为行和列索引时,出现输入不匹配异常。

【问题讨论】:

    标签: java file io


    【解决方案1】:

    问题的可能原因

    每当您使用 Scanner 类从用户那里获取输入时。如果传递的输入与方法不匹配或抛出 InputMisMatchException。例如,如果你使用 nextInt() 方法读取一个整数数据,然后传入一个 String 的值,就会发生异常。

    处理输入不匹配异常

    处理此异常的唯一方法是确保在传递输入时输入正确的值。建议在使用扫描仪类从用户读取数据时指定完整详细的所需值。

    【讨论】:

    • 啊,我现在明白了,我的数字在文件中是字符串格式的。有什么办法可以以整数格式检索它们?
    • 如果您确定扫描仪给您的是字符串而不是数字,请尝试将其读取为字符串“scan.next()”而不是 int,然后您可以将其解析为代码中的 int
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多