Scala:给定多个字符串,使用if语句查找给定字符串是在集合1、2中,还是不在集合1、2中
给定字符串:Scala:给定多个字符串,使用if语句查找给定字符串是在集合1、2中,还是不在集合1、2中,scala,Scala,给定字符串:“A”、“BDS”、“DE”、“BO”、“IID” 以下是我所拥有的: def givenStrings(code: List[String]) = { //val code = List("A", "BDS", "DE", "BO", "IID") if (code.contains("A", "BDS")) "It is in the first set"; else if(security_code.contains("DE",
“A”、“BDS”、“DE”、“BO”、“IID”
以下是我所拥有的:
def givenStrings(code: List[String]) = {
//val code = List("A", "BDS", "DE", "BO", "IID")
if (code.contains("A", "BDS"))
"It is in the first set";
else if(security_code.contains("DE", "BO", "IID"))
"It is in the second set";
else
"Not given";
}
givenStrings(List("A")) -> Should result in "It is in the first set"
givenStrings(List("DE")) -> Should result in "It is in the second set"
givenStrings(List("OOOOOO")) -> Should result in "Not given"
我得到的错误是
类型不匹配;
找到:字符串(“A”)
必需:List[String]
您编写的方法需要一个列表,但您正在传入一个字符串。因此,请将您的方法签名更改为:
def givenStrings(code: String) = {
现在,您将拥有一个需要字符串的方法,当您给它一个字符串时,它不会向您抱怨
现在,您也不希望过度写入传递给函数的代码值。你应该去掉那条线
最后,您不能开始调用变量
security\u code
。因此,将其改回简单的code
问题在于,您正在检查字符串是否包含列表,而您想要的恰恰相反
我相信这更接近你的需要
object Codes {
private val codes: Set[String] = Set("A", "BDS")
private val securityCodes: Set[String] = Set("DE", "BO", "IID")
def givenString(code: String): Unit = {
if (codes.contains(code)) {
println("It is in the first set")
} else if (securityCodes.contains(code)) {
println("It is in the second set")
} else {
println("Not given")
}
}
}
您好@YouSun,错误很明显您正在向函数传递一个
字符串,但它需要一个List[String]
,因为这就是您在这里声明它的方式:def givenstring(code:List[String])。另外,code和securitycode是误导hanks,我已将其更改为def givenstring(code:String)={if(code.contains)(“a”,“BDS”))“它在第一集中”;否则如果(code.contains(“DE”,“BO”,“IID”))“它在第二集中”;否则“未给出”;}givenStrings(“A”)但是我得到了“未给出”当它应该是“它在第一集中”谢谢,但是关键字contain不是set[String]的成员@YouSun my bad,它是包含的
,我编辑了答案-我为混淆道歉。PS:在本例中,contains
不是一个关键字,只是一个方法名。