bajro
bajro

Reputation: 1250

add user input to a list in Scala

import scala.collection.mutable.MutableList  

var x = false
while (!x) {
val list = MutableList[Any]()
val input = scala.io.StdIn.readLine("input pls:\n")
list += input
if (input == "end"){ x = true ; println("Bye!"); sys.exit}
if (input =="show") {println(list)}

}

So whenever I run this program and then enter "show" to print the list it only prints out "show" in the list but why not the other input I have done before? What do I have to change in order to store all the input into my list (append) till i type "show" or "end?

Upvotes: 0

Views: 1973

Answers (2)

Paul
Paul

Reputation: 27483

Scala 2.11.7 on Ubuntu 15.04 / OpenJDK8

I added a line feed "\n" removal function called .stripLineEnd thinking this was needed for the ifs to match, but apparently that is unnecessary and will work fine with or without.

From Documentation:

def stripLineEnd: String

Strip trailing line end character from this string if it has one.

A line end character is one of

LF - line feed (0x0A hex)

FF - form feed (0x0C hex)

If a line feed character LF is preceded by a carriage return CR (0x0D hex), the CR character is also stripped (Windows convention).

And, as @Mifeet said, the code was initializing the list on every loop and need to move the initialization to before the loop.

import scala.collection.mutable.MutableList  
var x = false
val list = MutableList[Any]()
while (!x) {
    val input = scala.io.StdIn.readLine("input pls:\n").stripLineEnd
    list += input
    if (input == "end"){ x = true ; println("Bye!"); sys.exit}
    if (input =="show") {println(list)}
}

Upvotes: 0

Mifeet
Mifeet

Reputation: 13648

All you need to do is move initialization of list variable up:

val list = MutableList[Any]()
while (!x) {
    // ...
}

The way you have it now, a new list is created in every loop iteration and thus previous content is lost.

Upvotes: 2

Related Questions