【问题标题】:String.contains(otherString) gives "unexpected type" [closed]String.contains(otherString) 给出“意外类型”[关闭]
【发布时间】:2013-02-19 10:55:07
【问题描述】:
String doubleSpace = " ";
String news = "The cat jumped. The dog did not.";
while (news.contains(doubleSpace) = true)
{
news=news.replaceAll(" ", " ");
}
上面将无法编译,报错“unexpected type.required:variable, found:value”
我不明白为什么,因为 String.contains() 应该返回一个布尔值。
【问题讨论】:
标签:
java
string
contains
bluej
【解决方案1】:
while (news.contains(doubleSpace) = true)
应该是
while (news.contains(doubleSpace) == true)
= 用于赋值
== 用于检查条件。
【解决方案2】:
您的 while 循环错误,如下所示。您正在使用赋值值进行分配,因此您得到了该错误。也无需与 true 进行比较,因为 contains(...) 函数本身将返回 true 或 false需要。
while (news.contains(doubleSpace))
{
news=news.replaceAll(" ", " ");
}
【解决方案3】:
编译出错
while (news.contains(doubleSpace) = true)
应该是
while (news.contains(doubleSpace) == true)
【解决方案4】:
字符串上的 .contains() 方法已经返回布尔值
所以你不应该应用比较
无论如何,如果您确实应用了应用布尔运算符 '==' 而不是 '='
所以你的代码可以
while (news.contains(doubleSpace) == true)
{
news=news.replaceAll(" ", " ");
}
或更准确地说
while (news.contains(doubleSpace))
{
news=news.replaceAll(" ", " ");
}