Java:串行端口枚举和for循环
下面的代码可以工作,但不是我写的。它查看计算机端口名称并尝试将其与指定字符串进行匹配(对于 RxTx 串行通信)。
我的问题是 for 循环内的语句的作用是什么?除了 for (initialize;condition test;iterator) statements; 之外,我从未见过任何其他安排;
本质上我是在问 (String portName : PORT_NAMES) 部分和“:”运算符的作用是什么?
private static final String PORT_NAMES[] = {
"/dev/tty.usbserial-A9007UX1", // Mac OS X
"/dev/ttyUSB0", // Linux
"COM4", // Windows
};
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
// iterate through, looking for the port
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
for (String portName : PORT_NAMES) {
if (currPortId.getName().equals(portName)) {
portId = currPortId;
break;
}
}
}
谢谢
The following code works however I did not write it. It looks through a computers port names and attempts to match one with a specified string (For RxTx serial communcation).
My question is what that the statement inside the for loop does? I have never seen any arrangement other then for (initialize;condition test;iterator) statement;
Essentially I'm asking what the (String portName : PORT_NAMES) part does and the the ":" operator does?
private static final String PORT_NAMES[] = {
"/dev/tty.usbserial-A9007UX1", // Mac OS X
"/dev/ttyUSB0", // Linux
"COM4", // Windows
};
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
// iterate through, looking for the port
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
for (String portName : PORT_NAMES) {
if (currPortId.getName().equals(portName)) {
portId = currPortId;
break;
}
}
}
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是
Java
for-each 语句。它只是迭代:
符号后指定的集合中的每个元素。This is the
Java
for-each statement. It justs iterates through every element of the collection specified after the:
sign.这就是我记得听说过的所谓“扩展 for”循环。它基本上相当于 C#“foreach”运算符的 Java 版本;它迭代 PORT_NAMES 枚举中的 String 对象。
编辑:链接 http://leepoint.net/notes-java/flow/loops/ foreach.html
It's what I remember having heard called the "extended for" loop. It's basically the Java equivalent of the C# "foreach" operator; it iterates through the String objects in the PORT_NAMES Enumeration.
EDIT: Linky http://leepoint.net/notes-java/flow/loops/foreach.html
这就是 Java for-each 构造,自 JDK 1.5 以来就为人们所熟悉。它基本上等价于:
因此,这是一种更好的迭代数组或集合的方法,而不是必须使用循环中其他任何地方都没有使用的索引变量。有关详细信息,请参阅 Oracle 文档:
http://download .oracle.com/javase/1,5.0/docs/guide/language/foreach.html
This is the Java for-each construct, which has been familiar since JDK 1.5. It is basically equivalent to this:
So this is a nicer way to iterate over an array or a collection than having to use an index variable which is not used anywhere else in the loop. For more information see the Oracle documentation:
http://download.oracle.com/javase/1,5.0/docs/guide/language/foreach.html