-1

I am getting a strange return for the below block of code (sets of integer values):

public String doubleChar(String str) {
String answer = "";
for (int i = 0; i < str.length(); i++) {
answer = answer + (str.charAt(i) + str.charAt(i));
}
return answer;
}

Opposed to the correct output value (a duplication of the strings chars) when I remove the parentheses enclosing the str.chatAt method calls in the first statement line of the loop:

answer = answer + str.charAt(i) + str.charAt(i);

Any help is appreciated, could not track down online.

Thanks

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724

1 Answers1

0

In Java char is an integral type. It appears you wanted String concatenation (that is String addition). You could use

public String doubleChar(String str) {
    String answer = "";
    for (int i = 0; i < str.length(); i++) {
        answer = answer + String.valueOf(str.charAt(i))
                + String.valueOf(str.charAt(i));
    }
    return answer;
}

or (my preference) a StringBuilder like

public String doubleChar(String str) {
    StringBuilder sb = new StringBuilder();
    for (char ch : str.toCharArray()) {
        sb.append(ch).append(ch);
    }
    return sb.toString();
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249