如何通过布尔值调用名称

时间:2013-02-22 12:31:21

标签: java boolean

我想叫出CEO = true的人的名字;在这种情况下是Tristen。 我该怎么做? 我已经将公共String名称和public boolean CEO转换为Static。

我想要达到的是它看起来像这样

system.out.printIn(“你的CEO是Tristen”);

public class business {

public static String name;
public String lastname;
public String email;
public String department;
public static boolean CEO;
public boolean employee;
public boolean assistant;
public boolean head;
public boolean manager;

public static void main(String[]args){


    business tristen;
    business jan;
    business robert;
    business kevin;
    business ben;

    tristen = new business();
    tristen.name = "Tristen";
    tristen.lastname = "Korsuize";
    tristen.email = " ";
    tristen.department = "Magic";
    tristen.CEO = true;
    tristen.employee = false;
    tristen.assistant = false;
    tristen.head = false;
    tristen.manager = false;

    jan = new business();
    jan.name = "Jan";
    jan.lastname = "Lindenberg";
    jan.email = "Jan002_003@hotmail.com";
    jan.department = "Magic";
    jan.CEO = false;
    jan.employee = false;
    jan.assistant = false;
    jan.head = false;
    jan.manager = true;

    robert = new business();
    robert.name = "Robert";
    robert.lastname = "Irving";
    robert.email = " ";
    robert.department = "Magic";
    robert.CEO = false;
    robert.employee = false;
    robert.assistant = true;
    robert.head = false;
    robert.manager = false;


    if(business.CEO = true){
        System.out.println("Your CEO is"+ " "+ business.name);
    }

    }

}

2 个答案:

答案 0 :(得分:3)

我会把人们放在一个集合中,然后重复一遍。

List<business> businesses = new ArrayList<business>();
// add people here...

foreach (business b : businesses) {
   if (b.isCEO()) {
     System.out.println(b);
   }
}

其他一些评论:

  1. Java命名约定建议您将类名称大写,例如Business
  2. 您的会员是公开的。我会通过构造函数将它们设为私有并实例化。这促进了封装--OO编程的一个关键特性。通过方法公开它们(隐藏实现)
  3. 询问对象是否是首席执行官 - 不要拉扯该领域并自行决定。见上面的例子
  4. 我会尽量不使用static。您拥有的所有信息都包含在您的对象中。

答案 1 :(得分:2)

CEOname字段不应该是静态的。静态字段表示该值赋予business类的所有实例,而不仅仅是单个实例。例如;

tristen = new business();
tristen.CEO = true;

jan = new business();
jan.CEO = false;  //CEO is now false for all instances of business (tristen and jan)

您可能希望在创建时将所有实例存储在某种Collection中,然后您可以遍历该集合并检查哪一个是CEO。