2

I've searched hours for this kind of problem, but I've got no luck.

In Java, I'm try to get this kind of output:

1, 2, 3

(without the use of StringBuilder)

The result I am getting is:

1, 2, 3,

with the code:

for(int i=1; i <= 3; i++){
    String output = "";
    output += i + ", ";
    System.out.print(output);
}

p.s I am not using any arrays for my code.

OneCricketeer
  • 126,858
  • 14
  • 92
  • 185
AldwinB
  • 31
  • 7
  • `String output = null; for(int i=1; i <= 3; i++) { if (null == output) output = i; else output += ", "+i; }` – Tibrogargan Sep 04 '16 at 02:17
  • 2
    Dupplicate of http://stackoverflow.com/questions/1515437/java-function-for-arrays-like-phps-join, no need to re-invent the wheel. – Frederik.L Sep 04 '16 at 02:32
  • @Frederik.L I'm sorry, but I think the one you are mentioning is for arrays. – AldwinB Sep 04 '16 at 02:59
  • Instead of *removing* it at the end, you should simply not *add* it when it's not necessary. I'd use the loop body `{ if (i>1) output+=", "; output += i; }` for this, but similar solutions have already been given in the comments and answers. – Marco13 Sep 04 '16 at 03:16
  • @AldwinB Items separated by commas are representing an array. So why don't you just store it inside an array so it is easier to read? By treating a set of numbers like an array, you won't go around manual if-else tricks for the last item. – Frederik.L Sep 04 '16 at 03:34
  • Why not use a StringBuilder? – OneCricketeer Sep 04 '16 at 03:36
  • @Frederik.L, cricket_007: we're still not discussing about arrays and StringBuilder, so it's not recommended to use them. – AldwinB Sep 04 '16 at 04:29
  • Part of SO is to help promote good practices around common technical issues. A good answer should also consider suggesting good alternatives to avoid those in the future if possible. As it is, an accumulated string representing an array will get you in trouble if you don't have an actual array behind it. So is it recommended to use them? Totally, unless you plan on making an app that will only display strings. Also, StringBuilder is faster than string copies. – Frederik.L Sep 04 '16 at 04:56
  • I am very sorry, but our professor at school will disregard out of the topic/lesson codes and teach an alternative without using those kinds of advance codes. – AldwinB Sep 04 '16 at 09:14

7 Answers7

2

From Java 8+, this can be achieved using join method.

String.join(",", list)

rajadilipkolli
  • 3,048
  • 1
  • 21
  • 43
1

be careful where you make the final print as you have an accumulator string variable that will serve to make the impression at the end in addition also consider where you declare your variables within the variable will be created for the few times iterate the for, preferably testify before the cycle

use substring takes two parameters start position, end position

String output = "";
 for(int i=1; i <= 3; i++){
  output += i + ", ";
}
System.out.print(output.substring(0, output.length()-2)); 
//obtains from 1, 2.3 and omit the, end with the length () - 1 as the final //position

ouput

1, 2, 3

Dev. Joel
  • 1,074
  • 1
  • 8
  • 13
1

Here is one variation which has only a single ternary expression in the loop to build the output you want.

String output = "";
for (int i=1; i <= 3; i++) {
    output += (i > 1) ? ", " + i : i;
}

System.out.print(output);
Tim Biegeleisen
  • 387,723
  • 20
  • 200
  • 263
  • Why the ternary, and not just `{ if (i>1) output+=", "; output += i; }` ? – Marco13 Sep 04 '16 at 03:17
  • @Marco13 The ternary expression gets everything on a single line. You can't just write code which works, you have to make it beautiful. – Tim Biegeleisen Sep 04 '16 at 03:27
  • Beauty is in the eye of the beholder, and I think that a good ol' `if` is more straightforward here. Particularly, I don't like that `i` appears *twice* - but maybe the ugliness of this is more visible when `i` is something like `"The element with index "+i+" of some list is "+list.get(i)`, and not so important in this simple case. – Marco13 Sep 04 '16 at 10:33
1

Though there may be many possible ways to doing this, but the one that I like most is where you don't introduce any unnecessary comparisons within the for loop.

So what you can do is for the first character only, you can directly put it in the string outside the loop, and for all the others, you can append ", <number>" with the original string.

String output = "1";

for(int i=2; i <= 3; i++){
    output += ", " + i;
}

System.out.print(output);
Raman Sahasi
  • 24,890
  • 6
  • 51
  • 66
0

Easy:

String output = "1";
for(int i=2; i <= 3; i++){
    output += ", " + i;
}
System.out.print(output)

That'll give you

1, 2, 3

No need to complicate the task. This kind of thing comes up all the time. Just treat the first case as a special case.

Austin D
  • 6,678
  • 2
  • 26
  • 34
0

Try this it is more easier, just check string length and if something in variable append separator:

String output = "";
for(int i=1; i <= 3; i++){
   if(output .length>0)
   {
     output +=',';
   }
   output += i;
   System.out.print(output);
}

Code snippet for JQuery:

var output = "";
for(var i=1; i <= 3; i++){
   if(output .length>0)
   {
     output +=',';
   }
   output += i;
   console.log(output);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
0

You can do it simply using java 8 stream api

List<Integer> list = new ArrayList<>();
   list.add(1);
   list.add(2);
   list.add(3);
String s = list.stream().map(i -> i.toString ()).collect(Collectors.joining(","));
Seeker
  • 882
  • 9
  • 16