Exercise 3-10 (Command-line arguments)

Chapter_3     Exercise_3-9 Show_Properties     Exercise_3-11







Exercise 3-10     TIJ, p. 61


Exercise 3-10: (2) 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.




Arguments.java


public class Arguments
{
public static void main(String[] args) throws Exception
{
System.out.println("args[0] = " + args[0]);
System.out.println("args[1] = " + args[1]);
System.out.println("args[2] = " + args[2]);
}
}
/*
javac Arguments.java
java Arguments
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 0 out of bounds for length 0 at Arguments.main(Arguments.java:5)

java Arguments Hello
args[0] = Hello
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 1 out of bounds for length 1 at Arguments.main(Arguments.java:6)

java Arguments Hello, guys!
args[0] = Hello,
args[1] = guys!
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 2 out of bounds for length 2 at Arguments.main(Arguments.java:7)

java Arguments How are you?
args[0] = How
args[1] = are
args[2] = you?

java Arguments How are you, friend?
args[0] = How
args[1] = are
args[2] = you,
*/





Notes:

main() now throws an Exception in case you provide less than 3 arguments on the command line.
First, we call  java Arguments  with no arguments, so we get an exception on line 5 of the source file: Arguments.main(Arguments.java:5), where we try to print the first command line argument:
System.out.println("args[0] = " + args[0]);
Then we call  java Arguments Hello  (with 1 argument), so we get an exception on line 6, where we try to print args[1] (the second argument from the command line), and so on.
When we provide at least 3 argument, the first 3 are printed.









Chapter_3     Exercise_3-9 BACK_TO_TOP Show_Properties     Exercise_3-11



Comments

Popular posts from this blog

Contents