(Kotlin)如何将哈希图输出保存到文件中

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了(Kotlin)如何将哈希图输出保存到文件中相关的知识,希望对你有一定的参考价值。

选择选项8时,我无法将哈希图的内容写入文件。我已成功读取文件,并利用各种功能来调整产品目录。但是,每次选择保存选项时。文件清除减去产品的1。

这是我的代码

var products = HashMap<Int, Pair<String, Double>>()
val fileName = "src/products.txt"
var inputFD = File(fileName).forEachLine 
    var pieces = it.split(",")
    products[ pieces[0].toInt() ] = Pair(pieces[1], pieces[2].toDouble())

fun main() 
        var menuItems = arrayOf(
                "View all products",
                "Add a new product",
                "Delete a product",
                "Update a product",
                "View highest priced product",
                "View lowest priced product",
                "View sum of all product prices",
                "Exit and save"
        )
        var quitOption = menuItems.size
        var userChoice = 0
        while (userChoice != quitOption) 
            println()
            userChoice = menu(menuItems, "\nPlease enter your selection: ")
            when (userChoice) 
                1 -> viewAll()
                2 -> addProduct()
                3 -> deleteProduct()
                4 -> updateProduct()
                5 -> viewHighestPricedProduct()
                6 -> viewLowestPricedProduct()
                7 -> sumAllProductPrices()

                else -> 
                    if (userChoice != quitOption) 
                        println("ERROR: Please select a valid menu option.")
                    
                    fileSave()
                
            
        


fun sumAllProductPrices() 
    viewAll()
    println()
    var sum = 0.0
    for( product in products) 
        sum += product.value.second
    
    println( "The sum of all the product prices is: $ "$%.2f".format( sum )")


fun viewLowestPricedProduct() 
    println()
    products.minBy  it.value.second ?.let 
        val (key, value) = it
        println("The highest priced product is: ")
        println()
        println("Item#    Description      Price")
        println("-----    -------------    -------")
        println( "$key      $"%-13s".format(value.first)    $ "$%.2f".format(value.second )" )
    


fun viewHighestPricedProduct() 
    println()
    products.maxBy  it.value.second ?.let 
        val (key, value) = it
        println("The highest priced product is: ")
        println()
        println("Item#    Description      Price")
        println("-----    -------------    -------")
        println( "$key      $"%-13s".format(value.first)    $ "$%.2f".format(value.second )" )
    


fun updateProduct() 
    viewAll()
    println()
    print( "Please enter the Item# of the product you would like to update: " )
    var updateItem = readLine()!!.toInt()

    if( products.containsKey(updateItem)) 
        print( "Please enter a new description of the item: " )
        var description = readLine()!!
        print( "Please enter a new price of the item: " )
        var price = readLine()!!.toDouble()
        products[updateItem] = Pair(description, price)
        println( "Thank you. The product has been updated." )
    else 
        println("Sorry. That item does not exist.")
    


fun deleteProduct() 
    viewAll()
    println()
    println( "Please enter the Item# of the product you would like to delete: ")
    var removeItem = readLine()!!.toInt()
    if( products.containsKey(removeItem)) 
        products.remove(removeItem)
        println("Thank you. The product has been removed.")
     else 
        println("Sorry. That item does not exist.")
    


fun addProduct() 
    var keyGen = ( 100..999 ).random()
    viewAll()
    println()
    if(products.containsKey(keyGen)) 
        keyGen = ( 100..999 ).random()
     else 
        print( "Please enter the description of the new item: " )
        var productName = readLine()!!
        print( "Please enter the price for $productName: ")
        var productPrice = readLine()!!.toDouble()
        products[keyGen] = Pair(productName, productPrice.toDouble())
        println( "Thank you. The product has been added." )
    


fun viewAll() 
    println()
    println("Item#    Description      Price")
    println("-----    -------------    -------")
    for( record in products.toSortedMap()) 
        println( "$record.key      $"%-13s".format(record.value.first)    $ "$%.2f".format( record.value.second )" )
    


fun menu(items: Array<String>, prompt: String): Int 
        for ((index, item) in items.withIndex()) 
            println("$index + 1. $item")
        
        print(prompt)
        return readLine()!!.toInt()

// Write method to write the hashmap back to the disk
fun fileSave() 
    var fd = File( fileName ).printWriter()
    for (record in products) 
        fd.println("$record.key,$record.value.first,$record.value.second")
        fd.close()
    
    println( "Thank you. The file has been saved.")

谢谢。感谢您为解决此问题所提供的帮助。

答案

将所有记录写入文件后,应关闭文件打印机。

fd.close()移出for循环。

for (record in products) 
    fd.println("$record.key,$record.value.first,$record.value.second")
    // fd.close() << from here

fd.close() // to here

以上是关于(Kotlin)如何将哈希图输出保存到文件中的主要内容,如果未能解决你的问题,请参考以下文章

如何将哈希图转换为数组?

如何将哈希图转换为条目数组[重复]

将哈希图转换为数组[重复]

如何将 JSON 元素输出到 Kotlin? [复制]

struts2 和 dojo 网格

如何将gcc的错误输出保存到文件