我在阅读的一本书中的许多例子中都看到了这一点,但作者并没有解释算法是什么? String host = args.length> 0? args [0]:" localhost&#34 ;;
import java.net.*;
import java.io.*;
public class Test {
public static void main(String[] args) {
String host = args.length > 0 ? args[0] : "localhost";//This is the part that I don't get
for (int i = 1; i < 1024; i++) {
try {
Socket s = new Socket(host, i);
System.out.println("There is a server on port " + i + " of "
+ host);
s.close();
} catch (UnknownHostException ex) {
System.err.println(ex);
break;
} catch (IOException ex) {
// must not be a server on this port
}
}
}
}
答案 0 :(得分:0)
您注释的行将host
字符串设置为第一个命令行参数,如果没有命令行参数,则设置为"localhost"
。
它使用三元运算符,它基本上扩展如下:
String host;
if (args.length > 0){
host = args[0];
}else{
host = "localhost";
}