在 Java 中,使用 将源代码编译为类文件javac sayagain.java
,然后创建一个sayagain.class
本质上是 JVM(Java 虚拟机)可以理解和执行的文件。
要运行sayagain.class
javac 命令生成的,您将使用java sayagain
您还可以将参数(以空格分隔)传递给正在运行的类,如下所示:
java sayagain Hello World !
这些参数被传递给您在主类中定义的args
数组,这是首先调用的方法。(您可以将其称为 listOfArguments,如下所示,它不会有任何区别)
要访问数组中包含的任何对象,请使用[]
. 数字从 0 开始,以长度 1 结束。这是您的代码的更改示例:
public class sayAgain {
//Eventhough there is two say methods, one takes a String parameter, and one takes an Integer parameter, thus they are different
public static void say(String s){
System.out.print(s);
}
public static void say(int i) {
System.out.print(i);
}
public static void main(String[] listOfArguments){
//First argument, starting at 0 - Hello
String arg1 = listOfArguments[0];
//Second argument - World
String arg2 = listOfArguments[1];
//Second argument - 3
String arg3 = listOfArguments[2];
//arg3 is a integer but is saved as a String, to use arg3 as a integer, it needs to be parsed
// Integer, is a class, just like your sayAgain class, and parseInt is a method within that class, like your say method
int count = Integer.parseInt(arg3);
//Print each argument
say(arg1);
say(arg2);
say(arg3);
//Use the converted argument to, to repeatedly call say, and pass it the current number
for (int t = 0; t < count; t++) {
//The variable t is created within the for structure and its scope only spans the area between the { }
say(t);
}
}
}
希望这可以帮助 :)