打印参数

89页Exercise 10

Write a program that prints three arguments taken from the command line. To do this, you'll nee to index into the command-line array of Strings.

public class Application {
    public static void main(String[] args) {
        if (args.length < 3) {
            System.err.println("Error: Please provide at least 3 command-line arguments");
            return;
        }
        
        System.out.println("First argument: " + args[0]);
        System.out.println("Second argument: " + args[1]);
        System.out.println("Third argument: " + args[2]);
    }
}

关键修改点:
添加了参数数量检查,确保至少有3个参数
直接通过数组索引访问前三个参数(索引0, 1, 2)
添加了明确的错误提示信息
运行方式:

java Application.java arg1 arg2 arg3

注意:如果参数包含空格,需要将参数用引号包裹:

java Application.java "first argument" "second argument" "third"
posted @ 2025-04-27 08:14  尼兰  阅读(7)  评论(0)    收藏  举报