페이지

2015년 10월 22일 목요일

Scala2e Chapter2 First Steps in Scala - Step5. Loop with while; decide with if

Step5. Loop with while; decide with if

To try out a while, type the following into a file named printargs.scala:

var i = 0
while (i < args.length) {
println(args(i))
i += 1
}

The first statement, println(args(i)), prints out the ith command line argument.
The second statement, i += 1, increments i by one. Note that Java’s ++i and i++ don’t work in Scala. i = i + 1 or i += 1.

$ scala printargs.scala Scala is fun

Scala
is
fun

For even more fun, type the following code into a new file with the name echoargs.scala:
var i = 0
while (i < args.length) {
if (i != 0)
print(" ")
print(args(i))
i += 1
}
println()

$ scala echoargs.scala Scala is even more fun

Scala is even more fun

Scala does use semicolons to separate statements as in Java, except that in Scala the semicolons are very often optional, giving some welcome relief to your right little finger.

echoargs.scala script as follows:

var i = 0;
while (i < args.length) {
if (i != 0) {
print(" ");
}
print(args(i));
i += 1;
}
println();

댓글 없음: