简体   繁体   中英

Returning a value in a specific format (java)

Not sure if the title explains what I really want to do, however,

I have a piece of information that currently prints out as

[[1/2, 1/2], 1]

however I need it to print out in the format

{{true@1/2, false@1/2}@1}

How would I go about doing this, I do have my toString method set up however I wasn't sure how to get the "true@" and remove the [[, I got the { however.

Currently I have,

@Override
public String toString() {
    String s = "{" + this.knowledge + "}";
    return s;

Any help would be much appreciated.

Regards,

Sim

I am assuming you have only access to a string (this.knowledge) of this format: [[str,str], str] , in that case the following solution will work:

@Override
public String toString() {
   StringBuilder strB = new StringBuilder();
    for (int i=0; i<this.knowledge.length(); i++) {
        if(this.knowledge.charAt(i)!='[' && this.knowledge.charAt(i)!=']' && this.knowledge.charAt(i)!=',') 
           strB.append(this.knowledge.charAt(i));
    }
    String[] strs = strB.toString().split("\\s+");
    return "{{true@" + strs[0] + ", false@" + strs[1]+ "}@" + strs[2] + "}";
}

Not sure if this answer explains what you really want to do, however,

The "piece of information" you have looks a lot like the default printout you might get from a list of lists. I was able to see something "similar" with:

List<String> inner = new ArrayList<String>();
inner.add("1/2");
inner.add("1/2");

List<Object> outer = new ArrayList<Object>();
outer.add(inner);
outer.add("1");

System.out.println(outer);

If it's correct to assume that knowledge is some known collection (of collections), you could create a format method that would be able to take the known elements and put them in the correct place. If "true" and "false" are hard-coded text strings, it might look like:

public String formatKnowledge(List list) {
    return "{{true@" + ((List)list.get(0)).get(0) + ", false@" + 
        ((List)list.get(0)).get(1) + "}@" + list.get(1) + "}";
}

Now clearly this would only work for that exact type of list input. If the list could be more complex, more complex logic would be needed to create the correct text (and braces) in the proper locations. Also if "true" and "false" are calculated somehow, that logic would also need to be added.

Disclaimer: The above format method is for illustrative purposes only. The author does not condone the use of crazy blind casts and crazier blind indexing...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM