Chapter 3, Exercises 7-8, Thinking in Scala
Here, we finally use an import statement, because I didn't want to say Math.floor(Math.random(...)). Exercise 8 just adds the infinite loop (shown in red here) to the code for exercise 7.
Here are the corresponding THECLAPP entries:
http://theclapp.blog-city.com/read/10083.htm
http://theclapp.blog-city.com/read/10086.htm
package x;
import Math.floor;
import Math.random;
object c3x7_and_8 {
def main ( args: Array[String] ) = {
while (true) {
val fr : Double = (floor(random() * 25.0));
val pivot : Int = fr.asInstanceOf[Int];
for (val i <- Iterator.range( 0, 25 ) ) {
val r : Int = (floor(random() * 25)).asInstanceOf[Int];
Console.println( r +
( if (r < pivot) " < ";
else if (r > pivot) " > ";
else " = "
)
+ pivot );
}
}
}
}
Note that the conversion of Float or Double to Int must be explicit. (That hole in C++ always bugged me.) And I pushed the if-expression into the inside of the println call.
11:43:53 PM