2016-12-16 4 views
1

Ich habe eine Textdatei, die ein paar Zeilen wie diese hat:Wie String-Liste [int] lesen, aus der Datei

SK1, 2, 3, 4, 5 
SK2, 1, 3, 5, 1 

ich sie lesen will, und speichern sie in einer Map [String, List [ Int]] aber mit dem Code, den ich geschrieben habe, erscheint er als Map [String, List [Any]] und ich weiß nicht, wie ich ihn beheben soll. Kannst du mir helfen?

def readFile(filename: String): Map[String, List[Any]] = { 

var mapBuffer: Map[String, List[Any]] = Map() 
try { 
    for (line <- Source.fromFile(filename).getLines()) { 
    val splitline = line.split(",").map(_.trim).toList 

    mapBuffer = mapBuffer ++ Map(splitline.head -> splitline.tail) 

    } 
} catch { 
    case ex: Exception => println("There was an exception, please try again.") 
} 
mapBuffer 
} 

Ich habe auch versucht

def readFile(filename: String): Map[String, List[Int]] = { 

var mapBuffer: Map[String, List[Int]] = Map() 
try { 
    for (line <- Source.fromFile(filename).getLines()) { 
    val splitline = line.split(",").map(_.trim).toList.map(_.toInt) 

    mapBuffer = mapBuffer ++ Map(splitline.head -> splitline.tail) 

    } 
} catch { 
    case ex: Exception => println("There was an exception, please try again.") 
} 
mapBuffer 
} 

aber das gibt mir Karte [Any, List [Int]]. Jede Hilfe wäre dankbar, danke.

+1

Und noch eine Glasgow HND Kurs Frage. Habt ihr keine Lerngruppe? –

Antwort

0
def readFile(filename: String): Map[String, List[Int]] = { 
    // map over lines in file 
    Source.fromFile(filename).getLines.map{ line => 
    // split the line into head and tail 
    val ::(head, tail) = line.split(",").map(_.trim).toList 
    // convert the tail to Int type 
    head -> tail.map(_.toInt) 
    } 
    .toMap // convert to Map 
}