1

我已经尝试了很多小时来解决数组任务,但在我看来,我被困住了。任务是创建一个程序,打印给定命令行参数的数量并列出它们。

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]);
       }

        }

    }

我要感谢所有回答这个问题的人,真的需要帮助!:)

4

2 回答 2

2

命令行参数不是程序读取的文本Scanner等,它们是在作为argsmain 参数的数组中指定的字符串。似乎您需要输出该数组的内容,而不是读取输入并输出它。

于 2013-07-25T11:35:33.070 回答
2

我认为您混淆了命令行参数的含义。命令行参数是main程序运行时传递给方法的参数,同时在程序运行时System.in在命令行捕获用户输入。

命令行参数在参数中传递给main方法,args例如:

java MyClass one two three

将数组["one", "two", "three"]作为args参数传递给main方法。

然后你所要做的就是使用args数组来打印你需要的数据信息。

于 2013-07-25T11:36:59.190 回答