faisal abdulai
faisal abdulai

Reputation: 3819

Scala code does not run in eclipse juno

I have been programming in java and new to scala . was trying my hands on some basic scala tutorials.I use eclipse Juno 4.2 with plugin for scala language. The JDK installed on the machine is 1.7.

the code below is for calculating sum of even fibonacci series below 4 million. when I run the code, the eclipse does not show any result and I am forced to terminate the process

var (a,b) = (1,2)
var sum = 0
while(a < 4000000)
{
if(a % 2 == 0)         
{ sum += a
val swap = a
a = b
b= swap + b}                            
}
println(sum)

on the other hand when I change the default value of variable a to 2 that is

var (a,b) = (2,2)

the system compiles and runs to give this answer 1383447424

don't know why eclipse Juno does not compile the scala code, when the variable a uses the default value of 1. The JDK installed on the machine is JDK 1.7.

Will be very glad to have explanations

Upvotes: 1

Views: 761

Answers (1)

dhg
dhg

Reputation: 52701

It does compile, and it's not an Eclipse issue.

The code has an infinite loop with a=1. If you format your code, you'll notice it looks like this:

var (a, b) = (1, 2)
var sum = 0
while (a < 4000000) {
  if (a % 2 == 0) {     <-- This scopes over everything in the loop!
    sum += a
    val swap = a
    a = b
    b = swap + b
  }
}
println(sum)

So the only thing in the while block is the conditional if(a%2==0). Since a=1, it is not a multiple of 2, and thus the code in the if never executes, and so it just goes round the loop without doing anything.

If you start with a=2 then a%2==0 is true, so the block executes, and you don't get the infinite loop. But it's not actually giving you the sum of even Fibonacci numbers like you want.

The problem is that the if-statement should only scope over the sum += a line.

var (a, b) = (1, 2)
var sum = 0
while (a < 4000000) {
  if (a % 2 == 0)
    sum += a
  val swap = a
  a = b
  b = swap + b
}
println(sum)

Upvotes: 6

Related Questions