使用||的Java调用方法

时间:2013-03-04 00:34:06

标签: java

这是我无法理解的一行

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 ...

3 个答案:

答案 0 :(得分:3)

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

这意味着

match(regex, s.substring(1))
当且仅当

时才会执行

match(regex.substring(1), s)

是假的。

所以返回值是:

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

答案 1 :(得分:0)

相当于:

if match(regex.substring(1), s) return true;
if match(regex, s.substring(1)) return true;
return false;

答案 2 :(得分:0)

您编写的程序使用5作为参数调用test。这打印出五个。这不超过4的10,所以它去了其他。在else中,你递归地调用它自己的方法,第一次使用4。所以打印4这会返回false。然后它尝试第二个是+ 1,所以它用6调用test。这在屏幕上打印6,掉到else,然后递归调用test,用a(现在是6)-1这样这个循环是无止境的。

你必须把第一个if:     if(a == 4)

这可以修复程序,但不能修复你想要的程序。

另外一个问题是你使用逻辑或完全错误。 OR用于查看两个答案中的一个是否为真。如果要根据情况调用方法,则必须使用if或三元运算符。

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
        if(test(a-1)) {
            return test(a-1);
        }
        else {
            return (test(a+1));
        }
}

这应该给你你想要的东西

相关问题