Home > Enterprise >  A string that is displayed as message conditioned by 3 booleans (java)
A string that is displayed as message conditioned by 3 booleans (java)

Time:12-15

I've searched on internet but I didn't find a good solution. I'm not a good developer soo may this will be too simple to somebody but I'm waisting too much time on solving that problem. In this project that I'm working on I need to build a string and this string is conditioned by 3 booleans, there is an example and my bad solution:

boolean a;
boolean b;
boolean c;

protected String getMessage(){
String result = "";

if(a){
  result  = "Problem A"
}

if(b){
  result  = ", Problem B"
}

if(c){
  result  = ", Problem C."
}

return result ;
}

So the problem is that maybe the only true boolean could be boolean C so the result message would be ", Problem C."

I'm asking for a good code quality that gives back a string and solve the problem of "," and "."

A solution that maybe somebody can give is to used nested if for example if (a && b) then "Problem A , Problem B." but in this case i need to implement 8 if conditions and the code complexity is bad.

Is there a smarter way to do what I'm asking for?

CodePudding user response:

You can use StringJoiner

     StringJoiner sj = new StringJoiner(", ", "", ".");
     sj.add("Problem1");
     System.out.println(sj.toString());
     
     sj.add("Problem2");
     System.out.println(sj.toString());

output

Problem1.
Problem1, Problem2.

CodePudding user response:

like this ?

boolean a;
boolean b;
boolean c;

protected String getMessage() {
    List<String> list = new ArrayList<>();

    if (a) {
        list.add("Problem A");
    }

    if (b) {
        list.add("Problem B");
    }

    if (c) {
        list.add("Problem C");
    }

    String result = String.join(", ", list)   ".";

    return result;
}

CodePudding user response:

This is a one way to do that.

 List list = new ArrayList();

    if (a) {
        list.add("Problem A");
    }

    if (b) {
        list.add("Problem B");
    }

    if (c) {
        list.add("Problem C");
    }

    return list.toString().replace("[", "").replace("]", ".");
  • Related