gpt4 book ai didi

Java调用方法使用||

转载 作者:行者123 更新时间:2023-11-29 05:47:45 27 4
gpt4 key购买 nike

这是我难以理解的行

return (match(regex.substring(1), s)|| match(regex, s.substring(1)));

我的理解是,如果第一个方法为假,它将调用后者。所以我写了一个简单的程序来测试。

public static void main(String[] args)
{
System.out.println(test(5));
}

public static boolean test(int a)
{
System.out.println(a);
if (a>10)
return true;
if (a==4)
return false;
else
return (test(a-1) || (test(a+1)));
}

但它只打印 5 4 6 5 4 6...

最佳答案

如果左边或右边的表达式为真,则逻辑或为真。如果左边的表达式为真,计算机语言可以选择不评估右边的表达式以节省时间。事实上,这正是 Java 所做的。

也就是说

match(regex, s.substring(1))

当且仅当

时才会执行
match(regex.substring(1), s)

是假的。

所以返回值为:

  • true 如果 match(regex.substring(1), s) 返回 true,
  • 的返回值匹配(regex, s.substring(1)否则

关于Java调用方法使用||,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15192748/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com