scala中是否有一个用于从列表中删除项目的功能? [英] Is there a function in scala used to remove items from a list?

查看:59
本文介绍了scala中是否有一个用于从列表中删除项目的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个待办事项列表,可以在其中添加和删除元素.我在尝试从可变列表中删除项目时遇到问题.

I am programming a todo list that I can add elements to and remove them as well. I am having problems trying to remove items from my mutable list.

val list = MutableList[Any]()

def removeItem(){
     val input = scala.io.StdIn.readLine("\nEnter item to remove:\n").stripLineEnd

    for(i <- 0 to list.size){
        if (list[i] == input){
           list[i] = 0
           list -= input
        }
    }

}


def menu(option: Int): Boolean = {
  option match {
    case 1 =>
      addItem()
      true
    case 2 =>
      println("Enter item to remove")
      removeItem
      true
    case 3 =>
      println("\nHere is your todo list:")
      display()
      true
    case 4 =>
      println("selected quit")
      false
    case _ => // the else case
      println("Unrecognized command")
      true
  }
}

当我从菜单中调用该功能以删除项目时,我希望我的删除项目功能能够遍历可变列表并删除其中=用户输入的项目,并允许我每次执行此操作我调用了该函数,但是却收到了这个错误:';'预期,但找到了'='. list [i] = 0

When I call the function from my menu to remove an item, I am expecting my remove item function to go through my mutable list and remove the item in it that is = to the user's input and allow me to do this each time I call the function, but I am getting this, error: ';' expected but '=' found. list[i] = 0

推荐答案

您可以尝试使用scala.collection.mutable.ListBuffer. 例子:

You can try using scala.collection.mutable.ListBuffer. Examples:

scala> import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ListBuffer

scala> var mutableList = new ListBuffer[String]()
mutableList: scala.collection.mutable.ListBuffer[String] = ListBuffer()

scala> println(mutableList)// empty
ListBuffer()

scala> mutableList += "First element"
res1: scala.collection.mutable.ListBuffer[String] = ListBuffer(First element)

scala> println(mutableList)// 1 element
ListBuffer(First element)

scala> mutableList += "second element"
res3: scala.collection.mutable.ListBuffer[String] = ListBuffer(First element, second element)

scala> println(mutableList)// 2 elements
ListBuffer(First element, second element)

scala> // Deleting...

scala> mutableList -= "First element"
res5: scala.collection.mutable.ListBuffer[String] = ListBuffer(second element)

这篇关于scala中是否有一个用于从列表中删除项目的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆