I am in the process of learning. I will be using StringBuilder for this problem, but this is bothering me.
The objective is to make a String from an array of Strings. The concat method doesn't work but the addition operator works.
This works:
public static void main(String[] args) {
String[] arr= {"1","2","3"};
String output ="";
for(String str: arr)
output+=str;
System.out.println(output);
}
But this doesn't concat method doesn't allow me to concatenate a String:
public static void main(String[] args) {
String[] arr= {"1","2","3"};
String output ="";
for(String str: arr)
output.concat(str);
System.out.println(output);
}
答案 0 :(得分:5)
The concat
method doesn't mutate the current String, but in fact returns a new String
containing the result.
Use it like this:
output = output.concat(str);
答案 1 :(得分:1)
You need to assign the return
of concat
.
for(String str: arr)
output = output.concat(str);
The method concat()
returns a String
of the concatenated results you just need to assign it to output
.