Reading from the terminalIntroduction to ScalaTuplesCommand line arguments

Command line arguments

Consider the following little script, triangle.scala:

def triangle(n: Int) {
  for (i <- 1 to n) {
    for (j <- 1 to i)  
	print("*")
    println()
  }
}

val size = 5
triangle(size)
As you can guess, it produces this output:
> scala triangle.scala 
*
**
***
****
*****
>
I can change the size of the triangle by editing the script and changing the value of size. Wouldn't it be much nicer if I could provide the size of the triangle when I call the script?

Command line arguments make this possible. Every time Scala executes a script, it takes all the arguments on the command line and packs them inside an array named args (for "arguments"). So we can change our script as follows:

val size = args(0).toInt
triangle(size)
And now we can run it as we like:
> scala triangle.scala 3
*
**
***
> scala triangle.scala 5
*
**
***
****
*****
> scala triangle2.scala 10
*
**
***
****
*****
******
*******
********
*********
**********

You can use as many command line arguments as you want (of course they have to fit on your command line when you enter them...). A simple test script is arguments.scala as follows:

for (s <- args)
  println(s)
And you could use it like this:
> scala arguments.scala I love CS109!
I
love
CS109!
> scala arguments.scala CS109    is    the best course at    KAIST... 
CS109
is
the
best
course
at
KAIST...
> scala arguments.scala
> scala arguments.scala 13 + 21
13
+
21
Note that the number of spaces between arguments doesn't matter—only the arguments themselves are passed inside args. Also notice that when I call the script without extra arguments, nothing is printed. That's because in this case args is an array of length zero, and so the for-loop does nothing.

Going back to our triangle.scala script, it's not perfect:

> scala triangle.scala
java.lang.ArrayIndexOutOfBoundsException: 0
  at Main$$anon$1.<init>(triangle2.scala:9)
  at Main$.main(triangle2.scala:1)
  at Main.main(triangle2.scala)
... and many more lines of error message.

What happened? I forgot to provide the size of the triangle, and so accessing args(0) failed.

So we should add some error checking to our script. Here is a better version:

if (args.length == 1) {
  val size = args(0).toInt
  triangle(size)
} else 
  println("Usage: scala triangle.scala <size>")
Now it behaves in a more civilized way:
> scala triangle.scala
Usage: scala triangle.scala <size>
The script is still not perfect, but we'll cover that later when we know more about exceptions.
Reading from the terminalIntroduction to ScalaTuplesCommand line arguments