ObjectInputStream并在Java中读取double

时间:2016-06-05 08:09:19

标签: java

public class Main {

    public static void main(String[] args)
    {
        /* Variables */
        int size = 10;
        Scanner keyboard = new Scanner(System.in);
        String fileName = "result.dat";
        ObjectInputStream inputStream;
        double[] d = new double[size];
        int j=0;

        /* Codes */
        try{
            inputStream = new ObjectInputStream(new FileInputStream(fileName));

            while(true) d[j++] = inputStream.readDouble();

            inputStream.close();

        }catch(FileNotFoundException e)
        {
            System.out.println(fileName+" found error");
            System.exit(0);
        }catch(IOException e){
            System.out.println(fileName+" reading error");
        }

    }
}

该程序从文件(result.dat)中读取10个双数字 我认为这些代码没问题。
但不幸的是,这些代码不起作用 如果我将while(true) d[j++] = inputStream.readDouble();更改为  for(i=0; i<size; i++) d[i] = inputStream.readDouble();,代码运作良好 我当然使用for句来解决这个问题。但我想知道。
那是为什么?

3 个答案:

答案 0 :(得分:1)

inputStream.close();无法访问。

while循环将继续,直到没有任何内容可读,然后它将抛出并发生错误并被捕获,此时IDE意识到它将永远不会运行inputStream.close();

for循环将起作用,因为它可以在没有抛出异常的情况下结束,并且inputStream.close();可以实际运行。

答案 1 :(得分:-1)

while循环的问题在于你永远不会退出&#34;循环,即使没有其他内容可读,所以你永远不会到达下一个语句(inputStream.close();)。

解决方案是在循环中添加j值的检查,如果测试为真,则添加break;语句,或者用while(true)替换while(j < 10)

从语义上讲,当您知道迭代次数时应使用for,并且当您不知道迭代次数时应使用while。在这里您可以知道迭代次数,因此for循环是最佳解决方案。

答案 2 :(得分:-1)

当您使用for循环时,您正在迭代size次。

for(i=0; i<size; i++) 

当您使用while循环时,您正在传递true,使其成为无限循环。

while(true)

因此,要使其工作,请将循环更改为 -

i = 0;
while(i < size){
// YOUR CODE GOES HERE
i++;
}