因此,学校已将我们转移到Java,而没有真正解释基础知识。
现在我有一个问题,我有一个方法equalsTest的类测试两个名称是否相同。然后在我的主要方法中,我必须调用equalsTest的结果并打印#34;同一个朋友"如果名称相同(equalsTest = true)和"不是同一个朋友"如果名称不同(equalsTest = false)
public class Person {
/* Attribute declarations */
private String lastName; // last name
private String firstName; // first name
private String email; // email address
public Person(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
//there are a few other methods in here but are not necessary for the issue explained
public boolean equalsTest(Person other){
if (this.firstName.equals(other.firstName)&& this.lastName.equals(other.lastName))
return true;
else
return false;
public static void main (String[] args) {
// create a friend
Person friend1 = new Person("Mickey", "Mouse", "");
friend1.setEmail("mickey@uwo.ca");
// create another friend
Person friend3 = new Person ("Mickey", "Mouse", "");
// create a friend without email
Person friend2 = new Person("Minnie", "Mouse", "");
//Here I need another method that calls the "true" or "false" boolean result of the equalsTest method above and says "if equalsTest true, print "Same Friend", and if equalsTest false, print "Not Same Friend", etc.
此外,实验室的部分要求是我可以编辑equalsTest方法,我必须在main方法中调用它。我知道在主方法中创建一个可以分析它的部分会更容易,但不能这样做。
答案 0 :(得分:0)
if(friend1.equalsTest(friend2)) {
System.out.print("Same");
}
else {
System.out.print("Not same");
}
答案 1 :(得分:0)
您将需要调用该函数并对方法调用的真实返回或错误返回执行某些操作。您可以使用简单的if / else。你也可以使用Ternary Operator,这对你只有两个你关心的结果非常有用。
(条件)? (的确如此):(假在这里)
String testResultOutput = "";
testResultOutput = friend1.equalsTest(friend3) ? "Friends are the same" : "Friends are NOT the same";
System.out.println(testResultOutput);
testResultOutput = friend2.equalsTest(friend3) ? "Friends are the same" : "Friends are NOT the same";
System.out.println(testResultOutput);
基于您的主要输出
Friends are the same
Friends are NOT the same
答案 2 :(得分:0)
您可以在主
中执行此操作if(friend1.equalsTest(friend2))
System.out.println("same");
else
System.out.println("not the same);
答案 3 :(得分:0)
我会添加一个打印方法,否则你总是需要调用equalsTest
方法。
public void printFriendsEqual(Person a) {
if (this.equalsTest(b)) {
System.out.println("Friends are the same");
} else {
System.out.println("Friends are NOT the same");
}
}
然后在main中调用它:
// create another friend
Person friend3 = new Person ("Mickey", "Mouse", "");
Person friend2 = new Person("Minnie", "Mouse", "");
friend3.printFriendsEqual(friend2);
答案 4 :(得分:0)
让你布尔方法静态... 现在你可以在条件语句中使用 if...else
public static boolean equalsTest(Person other){..}
private void myMethod(){
// Person other = new Person ("Mickey", "Mouse", "");
if(equalsTest(Person other)) {...}
}