0

I want to write a java program to get , a working C code as input, and clean it up. (we know that in the input, each line will not be more than one command(statement).)

#include <stdio.h>
int main(){
int i,n;
    float arr[100 ];
printf("Enter numbers:");
             scanf("%d",&n);
printf("\n");
for(i=0;i<n;++i)
{
printf("%d",i+1);
scanf("%f",&arr[i]);
}
for(i=1;i<n;++i){
if(arr[0]<arr[i])
arr[0]=arr[i];
}
printf("largest is %.2f",arr[0]);



return 0;
}

this is what I mean by clean up. The tabs in place, no redundant spaces, etc. the IDEs typically do this thing. but I want to write a code to do it myself.

#include <stdio.h>
int main(){
  int i, n;
  float arr[100];
  printf("Enter numbers:");
  scanf("%d", &n);
  printf("\n");
  for(i = 0; i < n; ++i){
    printf("%d", i + 1);
    scanf("%f", &arr[i]);
  }
for(i = 1; i < n; ++i){
  if(arr[0] < arr[i])
     arr[0] = arr[i];
  }
  printf("largest is %.2f", arr[0]);
  return 0;
}

I dont have much idea about where to begin.But I think I should use split and regex stuff, to first split the input into parts, and then parse it somehow. for example for dents(how many tabs for each "{") we should have a count of how many of "{" are inside each other, and things like that. 1) one dent for each block. 2) else comes directly after the "}" of an if, or if there is no "}", it comes in next line. 3)the character before ";" should be directly behind it(no separating space), also in a for, there is an space after ";"--> for(i=0; i++){.. 4)no redundant space. 5)no empty line

  • typically you would use ANTLR or JavaCC for this, not regexp. https://stackoverflow.com/questions/1639512/yacc-equivalent-for-java – neuhaus Mar 17 '15 at 12:36
  • Did not make code formatters before, but I think you need to make a lexical analyzer to format the code `properly`. Take a look at ANTLR: http://www.antlr.org/ –  Mar 17 '15 at 12:37
  • I "should" just use regex and nothing more. it is supposed to be a regex practice. – Iman Hosseini Mar 17 '15 at 12:39
  • "The tabs in place, no redundant spaces, etc." You need to be specific about the 'etc.' . If this is a regular expression exercise then it cannot be the type of code cleanup that an IDE does, it can only be a very specific subset of cleanup actions. – Gimby Mar 17 '15 at 13:13
  • you are right. I wrote down the actions. its only the most simple ones, about spacing and dents. – Iman Hosseini Mar 17 '15 at 13:22

0 Answers0