Java,三元运算符,if-then-else
问题描述:
我一直在使用Java来编写一个hang子手游戏。有人为我重新设计了这两种方法,然后离开了;这些方法必须工作,因为我的程序工作,我不知道他们做什么。Java,三元运算符,if-then-else
你能否向我解释这段代码,就好像你在为初学者评论它,并且提供了一个更简单的代码版本(也许更多的if-then-elses),它保持了相同的功能?
问题,答案,信息在类中声明,包含我遇到麻烦的两种方法。
public class Question {
private final String question;
private final String answer;
private final String info;
}
并在此构造函数中初始化...
public Question(String question, String answer, String info) {
this.question = question;
this.answer = answer;
this.info = info;
}
问题1的声明和命名HangmanMain这样不同的类初始化...
private static List<Question> initQuestions() {
Question question1 = new Question("What is the statement terminating character in Java?", ";", "The semi-colon (;) is used to end a statement in Java.");
}
两种方法我m遇到问题:
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Question question1 = (Question) o;
if (answer != null ? !answer.equals(question1.answer) : question1.answer !=
null) return false;
if (info != null ? !info.equals(question1.info) : question1.info != null)
return false;
if (question != null ? !question.equals(question1.question) :
question1.question != null) return false;
return true;
}
public int hashCode() {
int result = question != null ? question.hashCode() : 0;
result = 31 * result + (answer != null ? answer.hashCode() : 0);
result = 31 * result + (info != null ? info.hashCode() : 0);
return result;
}
答
equals()
方法严重过于复杂。你真的应该拆分成一个功能测试的东西平等领域,如
private static boolean equals(String a, String b) {
if (a == null) {
return b == null;
}
return a.equals(b);
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Question)) {
return false;
}
Question that = (Question) o;
return (equals(this.answer, that.answer) && //
equals(this.info, that.info) && //
equals(this.question, that.question));
}
然后,你可以从hashCode()
删除ternaries像
public int hashCode() {
int result = 0;
if (question != null) {
result = question.hashCode();
}
if (answer != null) {
result = 31 * result + answer.hashCode();
} else {
result = 31 * result;
}
if (info != null) {
result = 31 * result + info.hashCode();
} else {
result = 31 * result;
}
return result;
}
我会把这些方法还给你如何让他们最初,特别是'equals'方法。这是令人困惑的代码没有意义。除非你在像嵌入式系统这样高度专业化的领域工作,否则可维护性几乎是你的代码可以拥有的最重要的属性,并且包括能够轻松地阅读和理解它。 – 2014-11-02 07:49:48
三元组不会混淆。三元组返回一个基于条件的值:'String s = condition? “ifTrue”:“ifFalse”;'。什么让你的情况困惑是他如何嵌套表达。你应该把它分解,通过表达表达,以便轻松理解发生了什么。将某些语句存储在变量中。 '!answer.equals(question1.answer)'可以存储在一个布尔变量中。打破一切,它会更容易理解 – 2014-11-02 08:04:30