简体   繁体   English

尝试从文件中读取整数并将其存储在变量中时出现输入不匹配错误

[英]Getting an input mismatch error when trying to read an integer from a file and store it in a variable

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;
        
    }

This is currently my method to read a text file.这是目前我读取文本文件的方法。 Each text file has the matrix dimensions written at the top and then the rows of the matrix below.每个文本文件都在顶部写入矩阵维度,然后在下方写入矩阵的行。 Ex:前任:

2 3
1 1 1
2 2 2

When I try to store the first 2 numbers in the first row as the row and column indices, I get an input mismatch exception.当我尝试将第一行中的前 2 个数字存储为行和列索引时,出现输入不匹配异常。

Probable cause of your issue问题的可能原因

Whenever you take inputs from the user using a Scanner class.每当您使用 Scanner 类从用户那里获取输入时。 If the inputs passed doesn't match the method or an InputMisMatchException is thrown.如果传递的输入与方法不匹配或抛出 InputMisMatchException。 For example, if you reading an integer data using the nextInt() method and the value passed in a String then, an exception occurs.例如,如果您使用 nextInt() 方法读取整数数据并传入 String 中的值,则会发生异常。

Handling input mismatch exception处理输入不匹配异常

The only way to handle this exception is to make sure that you enter proper values while passing inputs.处理此异常的唯一方法是确保在传递输入时输入正确的值。 It is suggested to specify required values with complete details while reading data from user using scanner class.建议在使用扫描仪类从用户读取数据时指定具有完整详细信息的所需值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM