0
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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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)}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.