2

the method printDetails its prints out yes if the airCon field airCon is true,But I think this is not the perfect way of doing it, so is there any other way of doing it?

public class Auto
{
    private boolean airCon;
    public Auto() {}
    public void setAirCon(boolean airCon) {
        this.airCon = airCon;
    }

    public void printDetails() {
        String con;
        if(airCon) {
            con = "Yes";
        } else {
            con = "No";
        }
        System.out.println(con);    
    }
}
Kara
  • 6,115
  • 16
  • 50
  • 57
Ghassar Qhasar
  • 75
  • 1
  • 11

7 Answers7

4

Try a ternary:

System.out.println(aircon ? "Yes" : "No");

Ternary expressions are great for assigning something to either one value or the other based on a condition, all in one line. You can nest them too:

bool isConditionTrue, areYouSure;
string answer = isConditionTrue ? areYouSure ? "Yes" : "No" : "No";

which is a little easier read with parenthesis:

string answer =  isConditionTrue ? (areYouSure ? "Yes" : "No") : "No";

so the areYouSure boolean gets read only if the isConditionTrue boolean is true.

BrDaHa
  • 5,138
  • 5
  • 32
  • 47
3

Another way is to use the ternary operator:

String con = airCon ? "yes" : "no";

Same effect, less code.

P.S. You can of course move the whole expression into the println() if all you need to do is print it.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
3

That's a perfectly fine way to do it, if you want to save lines though you can use a ternary statement

System.out.println(aircon ? "Yes" : "No");
Jesus Ramos
  • 22,940
  • 10
  • 58
  • 88
2

This seems perfectly fine. The code is a little long, but that's not necessarily a bad thing.

You can use a handy Java trick to simplify it a lot:

public void printDetails()
{
    System.out.println(airCon ? "Yes" : "No");
}
Ina
  • 4,400
  • 6
  • 30
  • 44
0

use ternary operator.

String con=airCon?"yes":"no"
Biswajit
  • 2,434
  • 2
  • 28
  • 35
0

You have it correct. While your code is a bit verbose, it is best to go with what you understand. You could use a conditional statement:

System.out.println((airCon) ? "Yes": "No")

This does the same thing.

However, I would define a utility method in case you want to use it in other areas of your app.

public static String getYesNo(boolean input) {
   return ((input) ? "Yes": "No");
}

Here it would be better to make the "Yes" and "No" strings public static final's so they act as constants.

Pete B.
  • 3,188
  • 6
  • 25
  • 38
0

or you could use this, saves you an else:

public void printDetails()
{
String con = "No";
if(airCon)
{
    con = "Yes";
}
System.out.println(con);

}
CoderP
  • 1,361
  • 1
  • 13
  • 19