bigjoed
bigjoed

Reputation: 39

Scala Do While Loop Not Ending

I'm new to scala and i'm trying to implement a do while loop but I cannot seem to get it to stop. Im not sure what i'm doing wrong. If someone could help me out that would be great. Its not the best loop I know that but I am new to the language. Here is my code below:

def mnuQuestionLast(f: (String) => (String, Int)) ={
  var dataInput = true

  do {
    print("Enter 1 to Add Another 0 to Exit > ")
    var dataInput1 = f(readLine)

    if (dataInput1 == 0){
      dataInput == false
    } else {
      println{"Do the work"}
    }
  } while(dataInput == true)
}

Upvotes: 2

Views: 340

Answers (2)

Pooya
Pooya

Reputation: 4481

Your code did not pass the functional conventions. The value that the f returns is a tuple and you should check it's second value of your tuple by dataInput1._2==0

so you should change your if to if(dataInput1._2==0)

You can reconstruct your code in a better way:

import util.control.Breaks._


def mnuQuestionLast(f: (String) => (String, Int)) = {
  breakable {
    while (true) {
      print("Enter 1 to Add Another 0 to Exit > ")
      f(readLine) match {
        case (_, 0) => break()
        case (_,1) => println( the work"
        case _ => throw new IllegalArgumentException
      }
    }
  }
}

Upvotes: 1

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

You're comparing a tuple type (Tuple2[String, Int] in this case) to 0, which works because == is defined on AnyRef, but doesn't make much sense when you think about it. You should be looking at the second element of the tuple:

if (dataInput1._2 == 0)

Or if you want to enhance readability a bit, you can deconstruct the tuple:

val (line, num) = f(readLine)
if (num == 0)

Also, you're comparing dataInput with false (dataInput == false) instead of assigning false:

dataInput = false

Upvotes: 5

Related Questions