Java链接列表搜索方法中的三元运算符
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java链接列表搜索方法中的三元运算符相关的知识,希望对你有一定的参考价值。
我在Syntax error on token "=", != expected
得到了temp = temp.next
这是代码的其余部分
static boolean search(int xData) {
Node temp = head;
while (temp != null) {
return (temp.data == xData ) ? true : temp = temp.next;
}
return false;
}
答案
您正在尝试编写使用条件运算符无法完成的操作。
代替:
if (temp.data == xData) return true;
temp = temp.next;
return (temp.data == xData )? true : temp = temp.next ;
永远都会回来。毕竟,这是一份回报。所以,你的循环只会迭代一次。
您可以为作业括起来:
return (temp.data == xData )? true : (temp = temp.next);
然而:
- 您在返回之前立即重新分配了一个局部变量 - 重点是什么?
- 表达式的类型不是布尔值,因此它与方法的返回类型不兼容。
更好的方法是使用for循环:
for (Node temp = head; temp != null; temp = temp.next) {
if (temp.data == xData) return true;
}
return false;
另一答案
你无法用三元条件运算符表达这个逻辑,因为第二和第三个操作数有不同的类型(boolean
与Node
)。
此外,您似乎想要在条件为真时突破循环(使用return语句),否则保持循环,因此条件表达式没有意义。
static boolean search(int xData) {
Node temp = head ;
while(temp != null) {
if (temp.data == xData)
return true;
temp = temp.next;
}
return false ;
}
以上是关于Java链接列表搜索方法中的三元运算符的主要内容,如果未能解决你的问题,请参考以下文章