• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Code beautifying source code is not working correctly.

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is my code for prepare a string as a java source code. But it is not giving correct output. How can I fix it with this code?

String tab = "";
String code = "class Demo{public static void main(String[] args) {System.out.println(\"ABC\");if(\"A\".equals(\"A\")){return \"A\";}System.out.println(\"ABC\");}}";
String outtext = code;
String repfrom = "{";
String repto = "{\n";



Pattern p = Pattern.compile(repfrom, Pattern.LITERAL);
Matcher m = p.matcher(outtext);

int counter = 0;
StringBuffer sb = new StringBuffer();
while (m.find()) {
counter++;
m.appendReplacement(sb, repto + (tab += "\t"));
}
m.appendTail(sb);
String newtext = sb.toString().replace(";", ";\n");

System.out.println(newtext);

My output is

class Demo{
public static void main(String[] args) {
System.out.println("ABC");
if("A".equals("A")){
return "A";
}System.out.println("ABC");
}}


Thanks in Advance
 
Ranch Hand
Posts: 75
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please use the code tags where appropriate, I'm assuming you're wondering why your output is:

And I'm guessing you were looking for:

It appears that you are only adding the tabs after the "{\n" pattern, which would explain the non-tabbed lines, and it also appears that you are only adding other newlines after ";" which would explain the }} line.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic