Java的:循环上的两个布尔值(假,真) [英] java: looping on the two boolean values (false, true)

查看:429
本文介绍了Java的:循环上的两个布尔值(假,真)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个风格问题。我要循环两次,一个变量被设置为false,那么为true。哪一个是清晰的:

A)

 的(最终布尔上:新的布尔[] {假,真})
{
   doStuffBasedOnABooleanFlag(上);
}

B)

 的for(int i = 0;我2 ++ I)
{
   关于=最终布尔(我== 1);
   doStuffBasedOnABooleanFlag(上);
}

C)别的东西。


编辑:无意间pretations的墨菲定律进场......用例我原来看过这样的事情,而不是doStuffBasedOnABooleanFlag:

 的(最终布尔上:新的布尔[] {假,真})
{
   JButton的按钮=吗? onButton:offButton;
   button.addActionListener(新的ActionListener(){
      @覆盖公共无效的actionPerformed(ActionEvent的事件){
      doStuffLaterBasedOnABooleanFlag(上);
      }
   }
}

但我想我喜欢布伦丹的回答,我只是重构环内容到一个单独的方法:

  doStuffBasedOnABooleanFlag(假);
doStuffBasedOnABooleanFlag(真);   ...私人无效doStuffBasedOnABooleanFlag(对最终布尔)
{
   JButton的按钮=吗? onButton:offButton;
   button.addActionListener(新的ActionListener(){
      @覆盖公共无效的actionPerformed(ActionEvent的事件){
      doStuffLaterBasedOnABooleanFlag(上);
      }
   }
}


解决方案

由于它是两条线,我只是跳过循环,并做:

  doStuffBasedOnABooleanFlag(假);
doStuffBasedOnABooleanFlag(真);

减code,更明显,更高效。

This is a stylistic question. I want to loop twice with a variable on which is set to false, then to true. Which of these is clearer:

A)

for (final boolean on : new boolean[] { false, true} )
{
   doStuffBasedOnABooleanFlag(on);
}

B)

for (int i = 0; i < 2; ++i)
{
   final boolean on = (i == 1);
   doStuffBasedOnABooleanFlag(on);
}

C) something else


edit: Murphy's law of unintended interpretations comes into play... the use case I have originally looked something like this instead of doStuffBasedOnABooleanFlag:

for (final boolean on : new boolean[] { false, true} )
{
   JButton button = on ? onButton : offButton;
   button.addActionListener(new ActionListener() {
      @Override public void actionPerformed(ActionEvent event) {
      doStuffLaterBasedOnABooleanFlag(on);
      }
   }
}

But I think I like Brendan's answer, I'll just refactor the loop contents into a separate method:

doStuffBasedOnABooleanFlag(false);
doStuffBasedOnABooleanFlag(true);

   ...

private void doStuffBasedOnABooleanFlag(final boolean on)
{
   JButton button = on ? onButton : offButton;
   button.addActionListener(new ActionListener() {
      @Override public void actionPerformed(ActionEvent event) {
      doStuffLaterBasedOnABooleanFlag(on);
      }
   }
}

解决方案

Since it's two lines, I'd just skip the loop and do:

doStuffBasedOnABooleanFlag(false);
doStuffBasedOnABooleanFlag(true);

Less code, more obvious, more efficient.

这篇关于Java的:循环上的两个布尔值(假,真)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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