Terry
Terry

Reputation: 31

How to print the result of a method with System.out.println

How do I print out the result of a method? I want to print out the return of translate but it displays true or false. Suggestions please.

/**
     * @returns the string "yes" if "true" and "no" if false
     */
    public String translate(boolean trueOrFalse)    
       {       
        if(pback == true)
            {
                return "yes";
            }
        else
            {
                return "no";
            }
        }
    /**
     * Display book info
     */
    public void displaybook()
        {
            System.out.println("Title: " + title);
            System.out.println("Author: " + author);
            System.out.println("ISBN: " + isbn);
            System.out.println("Pages: " + pages);
            System.out.println("Paperback: " + pback);
            System.out.println("Suggested Price: " + price);            
        }

Upvotes: 0

Views: 38758

Answers (5)

Athens Holloway
Athens Holloway

Reputation: 2203

It looks like you mistakenly concatenated your variable pback instead of the result of your translate method in the following statement:

System.out.println("Paperback: " + pback); 

Instead, replace that statement with

System.out.println("Paperback: " + translate(pback)); 

Upvotes: 2

finnw
finnw

Reputation: 48619

public String translate(boolean trueOrFalse) {       
    if(pback == true) ...

Should probably be:

public String translate(boolean trueOrFalse) {       
    if(trueOrFalse) ...

Upvotes: 2

Adeel Ansari
Adeel Ansari

Reputation: 39897

Please don't forget to call the method, since you wrote it for some reason, I guess.

System.out.println("Paperback: " + translate(pback));

Now, few suggestions, do yourself a favour and change the method like below. if(pback == true), makes no sense. See, The Test of Truth, for your amusement.

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

Well, if you don't like ternary, do this,

public String translate(boolean pback) {
   if(pback) return "yes";
   else return "no";
}

If you like braces, put braces there,

public String translate(boolean pback) {
   if(pback) {
      return "yes";
   } else {
      return "no";
   }
}

If you don't like 2 return statements, do this,

public String translate(boolean pback) {
   String yesNo;
   if(pback) {
      yesNo = "yes";
   } else {
      yesNo = "no";
   }
   return yesNo;
}

Upvotes: 2

Marius
Marius

Reputation: 58921

public void displaybook()
    {
        System.out.println("Paperback: " + translate(pback));       
    }

Upvotes: 2

Jim Ferrans
Jim Ferrans

Reputation: 31012

System.out.println("Paperback: " + translate(pback));

Upvotes: 2

Related Questions