Issue
So, school has moved us on to Java, without really explaining the basics.
Right now I have an issue where I have a class with a method equalsTest that tests whether two names are the same. Then in my main method I have to call the results of equalsTest and print "Same friend" if the names are the same (equalsTest = true) and "not same friend" if the names are different (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("[email protected]");
// 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.
Also, part of the requirement for the lab is that I CANT edit the equalsTest method, I have to call it in the main method. I know it would be easier to just make a section in the main method that would analyze it, but can't do it.
Solution
You will want to call the function and do something on a true return or a false return of the method call. You can use a simple if/else. You can also use the Ternary Operator which is very useful for when you only have two outcomes you care about.
(condition) ? (true goes here) : (false goes here)
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);
Output based on your main would be
Friends are the same
Friends are NOT the same
Answered By - RAZ_Muh_Taz