0

I need to make a simple code, which get a string, and an array of String, and replace the ? signs with each element of array.

Here is the test case in junit:

@Test
    public void QueryFitterTest() {

        ArrayList<String> args=new ArrayList<String>(); 

        args.add("Bad code");
        args.add("The code is buggy");

        String res = QueryMaker.queryFitter("insert into  vulnerability (name,descirption) values(?,?)",args);
        String correctQuery="insert into  vulnerability (name,descirption) values(Bad code,The code is buggy)";
        assertEquals(correctQuery, res);

    }

and here is the code:

public static String queryFitter(String query, ArrayList<String> args){

    String[] colapsedQuery = query.split("");
    int parmNum=0;
    for(int i=0;i<colapsedQuery.length;i++){
        if(colapsedQuery[i]=="?"){
            colapsedQuery[i]=args.get(parmNum);
            parmNum++;
        }

    }

    query=concatenator(colapsedQuery);
    return query;

}
public static String concatenator(String[] colapsedQuery){
    String delimiter = "";
    String result = String.join(delimiter, colapsedQuery);
    System.out.println("query is: "+result);
    return result;
}

The code is working fine but

I don't like my approach, is there an easier way to do it?

Sal-laS
  • 11,016
  • 25
  • 99
  • 169

1 Answers1

0

There are 2 issues:

1- My code cannot pass the test, it returns the query without any change.

query is: insert into vulnerability (name,descirption) values(?,?)

2- I don't like my approach, is there an easier way to do it?

Well, the good news is that your JUnit test discovered a bug in your program. The other good news is that the answer to both of your questions is the same. Just fix your code in the method queryFitter.

Try the following code:

public static String queryFitter(String query, ArrayList<String> args){

   for(int i=0;i<args.size();i++){
      query = query.replaceFirst("\\?",args.get(i));
   } 

   return query;
}

Almost forgot to tell you. You don't need concatenator method either.

VHS
  • 9,534
  • 3
  • 19
  • 43