Herbert Schildt提到虽然这些方法没有任何技术上的错误, 枚举是一个更好的选择。
请考虑以下事项:
选择1:
//列举可能的答案。
enum Answers {
NO, YES, MAYBE, LATER, SOON, NEVER
}
public class Question {
Random rand = new Random();
Answers ask() {
int prob = (int) (100 * rand.nextDouble());
if (prob < 15)
return Answers.MAYBE; // 15%
else if (prob < 30)
return Answers.NO; // 15%
else if (prob < 60)
return Answers.YES; // 30%
else if (prob < 75)
return Answers.LATER; // 15%
else if (prob < 98)
return Answers.SOON; // 13%else
return Answers.NEVER; // 2%
}
}
public class AskMe {
static void answer(Answers result) {
switch (result) {
case NO:
System.out.println("No");
break;
case YES:
System.out.println("Yes");
break;
case MAYBE:
System.out.println("Maybe");
break;
case LATER:
System.out.println("Later");
break;
case SOON:
System.out.println("Soon");
break;
case NEVER:
System.out.println("Never");
break;
}
}
public static void main(String args[]) {
Question q = new Question();
answer(q.ask());
answer(q.ask());
answer(q.ask());
answer(q.ask());
}
}
选择2:
public interface SharedConstants {
int NO = 0;
int YES = 1;
int MAYBE = 2;
int LATER = 3;
int SOON = 4;
int NEVER = 5;
}
public class Question implements SharedConstants {
Random rand = new Random();
int ask() {
int prob = (int) (100 * rand.nextDouble());
if (prob < 30)
return NO; // 30%
else if (prob < 60)
return YES; // 30%
else if (prob < 75)
return LATER; // 15%
else if (prob < 98)
return SOON; // 13%
else
return NEVER; // 2%
}
}
public class AskMe implements SharedConstants {
static void answer(int result) {
switch (result) {
case NO:
System.out.println("No");
break;
case YES:
System.out.println("Yes");
break;
case MAYBE:
System.out.println("Maybe");
break;
case LATER:
System.out.println("Later");
break;
case SOON:
System.out.println("Soon");
break;
case NEVER:
System.out.println("Never");
}
}
public static void main(String args[]) {
Question q = new Question();
answer(q.ask());
answer(q.ask());
answer(q.ask());
answer(q.ask());
}
}
Herbert Schildt没有给出相同的理由。 我很困惑为什么关于枚举的选择更好?
答案 0 :(得分:3)
滥用int
这样的通用数字类型作为枚举绝不是一个好主意。考虑在Java中使用它的唯一原因是性能 - 当我说性能时,我的意思是纳秒。
你采用int
方法会失去很多:enum
是一个成熟的类,可以有任意方法,可以轻松简化和组织代码。您还可以获得全面的安全性。事实上,如此多的优点,如果我试图列举所有这些答案,这个答案会变得太长。
答案 1 :(得分:2)
您可以对所有可能的值更有信心。例如,当您执行int
版本时,您删除了其中一个选项。
您还可以包含更多信息,而不是通过代码分发
enum Answers {
NO("No", 0.30),
YES(Yes", 0.30),
MAYBE("Maybe", 0.15),
LATER("Later", 0.15),
SOON("Soon", 0.13),
NEVER("Never", 0.02);
private final String description;
private final double chance;
private Answer(String description, double chance) {
this.description = description;
this.chance = chance;
}
public String getDescription() { return description; }
public Answers getRandom() {
double r = Math.random();
for(Answer a : values())
if ((r -= a.chance) <= 0)
return a;
return NEVER;
}
}