Think in java 答案_Chapter 2_Exercise 7

来源:互联网 发布:趣凡网络如何 编辑:程序博客网 时间:2024/05/17 01:23

阅前声明: http://blog.csdn.net/heimaoxiaozi/archive/2007/01/19/1487884.aspx

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

public class E07_ShowArgs {
  public static void main(String[] args) {
    System.out.println(args[0]);
    System.out.println(args[1]);
    System.out.println(args[2]);
  }
}

//+M java E07_ShowArgs A B C

**Note that you’ll get a run-time exception if you run the program without enough arguments. You should actually test for the length of the array first, like this:

/****************** Exercise 7 ******************
* Testing for the length of the array first.
***********************************************/

public class E07_ShowArgs2 {
  public static void main(String[] args) {
    if(args.length < 3) {
      System.out.println("Need 3 arguments");
      System.exit(1);
    }
    System.out.println(args[0]);
    System.out.println(args[1]);
    System.out.println(args[2]);
  }
}

**The System.exit( ) call terminates the program and passes its argument back to the operating system as a result (with most operating systems, a non-zero result indicates that  the program execution failed)


//+M java E07_ShowArgs2 A B C

原创粉丝点击