【问题标题】:The ternary operator in Java Linked list Search methodJava链表搜索方法中的三元运算符
【发布时间】:2018-06-06 03:57:45
【问题描述】:

我在temp = temp.next 中有一个Syntax error on token "=", != expected

这是其余的代码

static boolean search(int xData) {

    Node temp = head; 

    while (temp != null) {
        return (temp.data == xData ) ? true : temp = temp.next;
    }

    return false;
}

【问题讨论】:

    标签: java linked-list ternary-operator ternary


    【解决方案1】:

    您正在尝试编写无法使用 条件 运算符完成的内容。

    改为:

    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;
    

    【讨论】:

      【解决方案2】:

      您无法使用三元条件运算符表达该逻辑,因为第二个和第三个操作数具有不同的类型(booleanNode)。

      此外,您似乎想在条件为真时跳出循环(使用 return 语句),否则留在循环中,因此条件表达式没有意义。

      static boolean search(int xData) {
      
          Node temp = head ; 
      
          while(temp != null) {
             if (temp.data == xData)
                 return true;
             temp = temp.next;
          }
      
          return false ;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-09-25
        • 2014-02-08
        • 2011-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多