Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write a method that translates a boolean into "yes" or "no"

Tags:

java

I'm new to java and I"m need to write a method that translates a boolean true or false into a string "yes" or "no". I'm kinda lost.

public class Book
{
    private String title;
    private String author;
    private String isbn;
    private int pages;
    private boolean pback;
    private double price;

    /**
     * Constructor for objects of class Book
     */
    public Book(String bookTitle, String bookAuthor, String bookCode, int bookPages, boolean paperback, double bookRetail)
    {
        // initialise instance variables
        title = bookTitle;
        author = bookAuthor;
        isbn = bookCode;
        pages = bookPages;
        pback = paperback;
        price = bookRetail;
    }


public String translate(boolean trueorFalse)
            {
                if(pback = true)
                    {
                        ??????;
                    }            
                 else(pback = false)
                    {
                        ???????;
                    } 

            }
like image 488
Tim Avatar asked Feb 07 '10 09:02

Tim


2 Answers

boolean myBoolean = true;
String result = myBoolean ? "yes" : "no";
like image 118
tangens Avatar answered Oct 19 '22 22:10

tangens


The conditional operator is your friend:

public static String translate(boolean trueOrFalse) {
    return trueOrFalse ? "yes" : "no";
}

In general, if you find yourself writing:

SomeType x;
if (someCondition) {
    x = someExpression;
} else {
    x = someOtherExpression;
}

it's generally nicer to use:

SomeType x = someCondition ? someExpression : someOtherExpression;

The conditional operator makes sure that only one of someExpression or someOtherExpression is evaluated, so you can use method calls etc, confident that they won't be executed inappropriately.

Of course there are times when this gets too complicated - you need to judge the readability of each form for yourself.

like image 41
Jon Skeet Avatar answered Oct 19 '22 23:10

Jon Skeet