java – 为什么有人会像这样构造一个while循环?
发布时间:2020-12-15 05:00:08 所属栏目:Java 来源:网络整理
导读:我正在读一本关于 Java的书,我们正在从一个频道读到一个ByteBuffer.我找到了作者构造while循环奇数的方式: try (FileChannel inCh = (FileChannel) Files.newByteChannel(file)) { ByteBuffer lengthBuf = ByteBuffer.allocate(8); int strLength = 0; Byte
我正在读一本关于
Java的书,我们正在从一个频道读到一个ByteBuffer.我找到了作者构造while循环奇数的方式:
try (FileChannel inCh = (FileChannel) Files.newByteChannel(file)) { ByteBuffer lengthBuf = ByteBuffer.allocate(8); int strLength = 0; ByteBuffer[] buffers = { null,ByteBuffer.allocate(8) }; while(true) { if(inCh.read(lengthBuf) == -1) break; lengthBuf.flip(); strLength = (int)lengthBuf.getDouble(); buffers[0] = ByteBuffer.allocate(2*strLength); if(inCh.read(buffers) == -1) { System.err.println("EOF found reading ht eprime string."); break; } System.out.printf("String length: %3s String: %-12s Binary Value: %3d%n",strLength,((ByteBuffer) (buffers[0].flip())).asCharBuffer().toString(),((ByteBuffer)buffers[1].flip()).getLong()); lengthBuf.clear(); buffers[1].clear(); } System.out.println("nEOF reached."); } catch (IOException e) { 我试过这样的: while(inCh.read(lengthBuf) != -1) { 它的工作方式相同.是否有一个实际或代码清晰的原因,作者会像他一样写出来? 解决方法
很明显,你的循环版本在语义上是相同的.但是,这不是唯一要考虑的事情.
请注意,在while循环的下方还有第二个条件会突破循环.我怀疑这是推动作者使用的原因(真实). 通过将其写为while(true),您可以提醒读者,内部必须有一个或多个断点.读者将不得不在循环内部查看休息时间,并希望能够找到它们. 写你的方式,随意的读者可能会扫描代码的顶部,并假设while条件是循环终止的唯一方法. 要考虑的另一点是对称性或平衡性.正如原作者所写,循环终止都是相同的形式.即从循环内打破.你的版本感觉不对称. while测试中的一个终止点,以及循环内的不同性质的另一个终止点. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |