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)
{
???????;
}
}
boolean myBoolean = true;
String result = myBoolean ? "yes" : "no";
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With