我是一名Java初學者,對於在許多代碼開始時測試args.length以及爲什麼在我的任何代碼中從未獲得高於0的代碼感到困惑?爲什麼測試args.length?
import java.net.Socket;
import java.net.UnknownHostException;
import java.io.IOException;
public class LowPortScanner {
public static void main(String[] args) {
String host = "localhost";
if (args.length > 0) {
host = args[0];
}
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);
}
catch (UnknownHostException ex) {
System.err.println(ex);
break;
}
catch (IOException ex) {}
} // end for
} // end main
} // end PortScanner
提供命令行參數和計數將可靠地上升。 – 2013-03-01 10:33:05