没有赋值的Java三元组 [英] Java Ternary without Assignment

查看:293
本文介绍了没有赋值的Java三元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在没有做任务的情况下进行java三元操作或假装分配?

Is there a way to do a java ternary operation without doing an assignment or way to fake the assingment?

我喜欢简单的三元代码在做一堆时看起来如何if / then / elses。

I like how succinct ternary code looks when doing a bunch of if/then/elses.

我希望能够根据布尔代数语句调用两个void函数之一。

I'm hoping to be able to call one of two void functions based on a boolean algebra statement.

类似于:

(bool1&& bool2)? voidFunc1():voidFunc2();

我的函数是返回类型 void ,所以如果有一种方法可以在作业中伪造它,那么我就可以了......我想看看如何做到这一点:)

My functions are of return type void, so if there is a way to fake this in an assignment to make it work, then I"m okay with that... I would like to see how to do it though :)

推荐答案

不,你不能这样做。规则如此说明


条件运算符有三个操作数表达式。?出现$ b第一个和第二个表达式之间的$ b,和:出现在
秒和第三个表达式之间。

The conditional operator has three operand expressions. ? appears between the first and second expressions, and : appears between the second and third expressions.

第一个表达式必须是boolean或Boolean类型,或者发生
编译时错误。

The first expression must be of type boolean or Boolean, or a compile-time error occurs.

第二个或第三个操作数的编译时错误
表达式是 void 方法的调用。

S.你问过反思,这是一个解决方案。我不推荐这个。我发帖只是因为你问过。

Since you asked about reflection, here's a solution. I'm not recommending this. I'm posting it only because you asked.

public class MyCall
{

    public void a(){System.out.println("a");}
    public void b(){System.out.println("b");}

    public static void main(String... args)
    {
        new MyCall().go();
    }

    public void go()
    {
        Class<? extends MyCall> class1 = this.getClass();
        Method aMethod = class1.getMethod("b", null);
        Method bMethod = class1.getMethod("a", null);
        Object fake = false ? aMethod.invoke(this, null) : bMethod.invoke(this, null);
        Object fake2 = true ? aMethod.invoke(this, null) : bMethod.invoke(this, null);
    }
}

在一天结束时你必须问自己是否提高了代码的可读性(想想 - 每个循环)。这些解决方案都没有提高代码的可读性恕我直言。如果我是你,我宁愿选择这个。

At the end of the day you've got to ask yourself if being succint improves your code's readability (think for-each loop). None of these solutions improve the code's readability IMHO. If I were you I'd rather go with this.

if(condition)
    a();
else
    b();

我实际上 包括大括号,即使循环只包含一个但是,由于你要使用清晰的代码,上面的代码段应该可以。

I'm actually for including braces even when loops only contain a single line, but since you're going after crisp code, the snippet above should do.

这篇关于没有赋值的Java三元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆