谁能解释一下这个算法?
Can anyone explain this algorithm please?
我在看的一本书的很多例子里看到了这个,但是作者没有解释算法是什么?字符串主机 = args.length > 0 ?参数 [0] : "localhost";
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
}
}
}
}
您评论的行将 host
字符串设置为第一个命令行参数或 "localhost"
(如果没有命令行参数)。
它使用了三元运算符,基本展开如下:
String host;
if (args.length > 0){
host = args[0];
}else{
host = "localhost";
}
我在看的一本书的很多例子里看到了这个,但是作者没有解释算法是什么?字符串主机 = args.length > 0 ?参数 [0] : "localhost";
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
}
}
}
}
您评论的行将 host
字符串设置为第一个命令行参数或 "localhost"
(如果没有命令行参数)。
它使用了三元运算符,基本展开如下:
String host;
if (args.length > 0){
host = args[0];
}else{
host = "localhost";
}