从文件中使用扫描仪时出现InputMismatch

问题描述

晚上好。我正在尝试从文件中读取双精度数据并将它们放入双精度数组。我解决此问题的方法是使用扫描仪。

这是我的代码

public static void decryption(int n,int d) throws IOException
    {
        String encFile = getFile();
        String decFileName = getNewFile();
        
        //create save file for encrytped message
        File encFileSave = new File(decFileName);
        if(encFileSave.createNewFile())
        {
            System.out.println("Decrypted file created");
        }
        else
        {
            System.out.println("File already exists");
        }
                
        FileInputStream inS = new FileInputStream(encFile);
        //FileOutputStream outS = new FileOutputStream(decFileName);
        FileWriter outW = new FileWriter(decFileName);
        
        Scanner in = new Scanner(new File(encFile));
        int en = in.nextInt();
        double[] pmMess = new double[en];
        for(int i = 0; i < pmMess.length; i++)
        {
            pmMess[i] = in.nextDouble();
        }
        String dMess = decrypt(pmMess);
        
        outW.write(dMess);
    
        inS.close();
        outW.close();
        //end deccrypt
    }

我在行上收到错误“ InputMismatchException”

int en = in.nextInt();

这是我第一次遇到此特定错误,到目前为止,文档已经说过解决该问题的方法并不是一开始就做的。

我还尝试了FileInputStream,但没有成功。

输入如下

[373248.0,1030301.0,1259712.0,1367631.0,32768.0,658503.0,1481544.0,1000000.0,97336.0,2197.0,1000.0,474552.0,1157625.0,970299.0,314432.0,912673.0,1771561.0,35937.0,274625.0,1331000.0,1061208.0,1560896.0,1124864.0,1520875.0,1685159.0,1601613.0,941192.0,195112.0,68921.0,91125.0]

最终解决的问题

获取了输入文件内容,并使用正则表达式从本质上过滤了方括号和逗号。然后在遇到空格时也进行同样的操作以换行。

这是我用来做的代码

String bracOut;
while(bIn.ready())
{
    bracOut = bIn.readLine();
    String noBrac = bracOut.replaceAll("[,\\[\\]]","");
    noBrac = noBrac.replaceAll(" ","\n");
    byte[] noBracByte = noBrac.getBytes();
            
    outS.write(noBracByte);
    System.out.print(noBrac);
}

完成此操作后,我就能逐行读取每个双精度数据并将它们放入一个双精度数组。

解决方法

最终解决的问题

我获取了输入文件的内容,并使用正则表达式从本质上过滤了方括号和逗号。然后在遇到空格时也进行同样的操作以换行。

这是我用来做的代码。

String bracOut;
while(bIn.ready())
{
    bracOut = bIn.readLine();
    String noBrac = bracOut.replaceAll("[,\\[\\]]","");
    noBrac = noBrac.replaceAll(" ","\n");
    byte[] noBracByte = noBrac.getBytes();
            
    outS.write(noBracByte);
    System.out.print(noBrac);
}

完成此操作后,我就能逐行读取每个双精度数据并将它们放入一个双精度数组。