我只是一个用 Java 编写程序的初学者。如何将参数 (Array of strings)
传递给 main 方法?我使用 Eclipse 作为 IDE
public static void main(String[] args) {
// TODO Auto-generated method stub
if (args[0].equals("-h"))
System.out.print("Hello,");
else if (args[0].equals("-g"))
System.out.print("Goodbye,");
// print the other command-line arguments
for (int i = 1; i < args.length; i++)
System.out.print(" " + args[i]);
System.out.println("!");
}
Run > Run Configurations > Java Application > Arguments > Program
arguments
此外,请确保您的代码在未传递任何参数时都能正常工作,不要直接从数组中选取值。
public static void main(String[] args) {
// TODO Auto-generated method stub
if (args != null && args.length > 0) {
if (args[0].equals("-h"))
System.out.print("Hello,");
else if (args[0].equals("-g"))
System.out.print("Goodbye,");
// print the other command-line arguments
for (int i = 1; i < args.length; i++)
System.out.print(" " + args[i]);
} else{
System.out.print("No Arguments passed");
}
System.out.println("!");
}