shewontreply
shewontreply

Reputation: 51

Method not returning desired value

I'm trying to write a method that takes an input string, and adds a character to it at a specified position. The inputString is 42 characters long, and is divided into 7 "columns", when the input is given by the user, the method should take that input and place an "X" into the appropriate position. Here is the code:

private String enterToken(String tokenSymbol, String inputString, int column){
   String columnEdit = inputString.substring(column*6-6,column*6); 

   String columnEdit1 = columnEdit.trim();
   String columnEdit2 = columnEdit1+tokenSymbol+"                 ";
   String columnEdit3 = columnEdit2.substring(0,6);
   String start = inputString.replace(inputString.substring(column*6-6,column*6),columnEdit3);
   System.out.println(start);
   return start;

 }

When I give it an input of 42 spaces and I give it a column 2, for example, it gives me an output of

"X     X     X     X     X     X     X     "

whereas it SHOULD give me one like

"      X                                   " 

Any ideas?

Upvotes: 1

Views: 99

Answers (2)

Olivier Croisier
Olivier Croisier

Reputation: 6149

Here is a solution :

private String enterToken(String tokenSymbol, String inputString, int column) {
    int colWidth = inputString.length() / 7;
    int tokenPos = (column-1) * colWidth;
    String inputStart = inputString.substring(0, tokenPos);
    String inputEnd = inputString.substring(tokenPos+1);
    return inputStart + tokenSymbol+inputEnd;
}

Upvotes: 0

user684934
user684934

Reputation:

You're calling replace on the whole string, instead of just the substring that you want to perform the operation on. i.e. inputString.replace(...)

You'll want to split the string, call replace on the substring, and then concatenate the strings back together for returning.

Upvotes: 1

Related Questions