0

I'm making some assignments and I've stumbled upon something I can't seem to fix.

So I made an enum class containing all the days of the week, and gave them a corresponding parameter to output the String value of the enums inside.

public enum Day{ Monday("monday");}

I then made the String to my enums final and made a constructor for it.

private final String day;

Day (String aDay) { this.day = aDay; }

Now I had to make a method that checks if it's a weekday or if it's a day in the weekend. I had to use a boolean for this.

    private boolean isWeekday() {
    if (this.getDay().equals("saturday") || this.getDay().equals("sunday")) {
        return false;
    } else {
        return true;
    }
}

Now this part is where I'm struggling right now. I had to make a toString method that returns the day and if it's a weekday or not.

The output should be like this:

monday(weekday) or sunday(weekend)

My method "isWeekday" will obviously only return true's or false's at this point. How can I let it print out weekday when it's true and weekend when it's false?

    public String toString() {
    return String.format("%s(%s)", this.getDay(), ??;
}

Thanks in advance, I've tried searching Google but I haven't had any succes.

1
  • Use the ternary operator. Commented Dec 28, 2013 at 16:27

1 Answer 1

3

You can use the ternary operator (also called conditional operator):

public String toString() {
    return String.format("%s(%s)", this.getDay(), isWeekDay() ? "(weekday)" : "(weekend)");
}

Relevant part:

isWeekDay() ? "(weekday)" : "(weekend)"

This basically results in

if(isWeekDay()) { 
    return "(weekday)";
} else {
    return "(weekend)";
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.