我已经尝试了很多小时来解决数组任务,但在我看来,我被困住了。任务是创建一个程序,打印给定命令行参数的数量并列出它们。
You gave 2 command line parameters.
Below are the given parameters:
1. parameter: 3455
2. parameter: John_Smith
我的程序从错误的索引开始 + 我不确定给定的任务。如果尚未初始化,程序如何知道要使用多少个参数?或者我只是完全迷失了这个练习?
这就是我所做的:
import java.util.Scanner;
public class ex_01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner reader = new Scanner(System.in);
int param = reader.nextInt();
String[] matrix = new String[param];
for (int i = 0; i < matrix.length; i++) {
matrix[i] = reader.nextLine();// This is the part where my loop fails
}
System.out.println("You gave " + matrix.length
+ " command line parameters.\nBelow are the given parameters:");
for (int i = 0; i < matrix.length; i++) {
System.out.println(i + 1 + " parameter: " + matrix[i]);
}
}
}
还有我自己的输出:
3 //This is the number of how many parameters the user wants to input
2 // Where is the third one?
omg //
You gave 3 command line parameters.
Below are the given parameters:
1 parameter:
2 parameter: 2
3 parameter: omg
编辑:
我做的!我做的!!经过更多谷歌搜索后,我发现了这个:
if (args.length == 0) {
System.out.println("no arguments were given.");
} else {
for (String a : args) {
}
}
然后我只是修改了程序并编译了程序。这是整个程序:
import java.util.Scanner;
public class Echo {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("no arguments were given.");
} else {
for (String a : args) {
}
}
System.out.println("You gave " + args.length
+ " command line parameters.\nBelow are the given parameters:");
for (int i = 0; i < args.length; i++) {
System.out.println(i + 1 + ". parameter: " + args[i]);
}
}
}
我要感谢所有回答这个问题的人,真的需要帮助!:)