0

I'm running into this problem where if want to loop through an array and print out its contents separated by a comma, it prints out an extra at the end. I did some searching but, couldn't find an answer that worked for this situation.

Code:

public String toString(){

    String hold= "";
    for(int i = 0; i < array.length; i ++){

        if(array[i] == true){
            hold + = i;
            if(i != array.length-1)
                hold+= ",";
        }
    }
    return hold;
}
Jared E.
  • 1
  • 1
  • 3
  • Just check if the current iteration is the last one as in: if (i == arr.length - 1) System.out.print(element); else System.out.print(element + ", "); –  Nov 29 '17 at 02:12
  • for the occasional loop I use a boolean which gets set on the first loop and inserts a comma on every other loop. but iv been writing a code generator recently where this pattern comes up a lot, so i made a class to represent it. internally is maintains and boolean to determine if its 'print' method has been called more than once. only then it outputs the required value (passed in on the constructor). – slipperyseal Nov 29 '17 at 02:40

6 Answers6

1

in Java 8, you don't need this at all anymore: If its Array of string then following will give you same thing you want to achieve.

String joined = String.join(",", name);

how-to-convert-array-to-comma-separated-string

Another way Java 8, would be

List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7);

    System.out.println(numbers.stream()
        .map(number -> String.valueOf(number))
        .collect(toStringJoiner(", ")));
Mahendra Kapadne
  • 426
  • 1
  • 3
  • 10
0

After the loop just check if it ends with a comma

for(whatever){
  whatever
}
if(hold.endsWith(","){
  hold = hold.substring(0,hold.length()-1);
}

EDIT:

String arrayString = Arrays.toString(my_array)
arrayString = arrayString.substring(1,arrayString.length()-1) // gets rid of the '[]'
Solace
  • 2,161
  • 1
  • 16
  • 33
0

Maybe the last array[i] is not true so your logic testing for

if(i != array.length-1)

is not entered into.

But anyway simply replace

if(hold.endsWith (","){
  hold = hold.substring (0, hold.length()-1);
}
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

Try this

      public String toString(){
            String hold= "";
            for(int i = 0; i < array.length; i ++){

                if(array[i] == true){
                    if (i != 0) {
                        hold += ",";
                    }
                    hold += i;
                    // if(i != array.length-1) {
                    //   hold+= ",";
                    // }
                }
            }
            return hold;
        }

Herupkhart
  • 499
  • 4
  • 23
0

it's very easy with Java 8:

String[] values={"foo", "bar", "baz"};

public String toString(){
    return Arrays.stream(values).collect(Collectors.joining(", "));
}

pre-Java 8 I'd go for this verbose way:

public String toString(){
    StringBuilder sb = new StringBuilder();
    Iterator<String> iterator = Arrays.asList(values).iterator();
    if(iterator.hasNext()){
        sb.append(iterator.next());
        while(iterator.hasNext()){
            sb.append(", ").append(iterator.next());
        }
    }
    return sb.toString();
}
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
0

Hope this helps (You can grab the logic and integrate with your code)

String op = "";
for (int i = 0; i < arr.length; i++) {
    op += i != 0 ? ", " + arr[i] : arr[i];
}
Amit Phaltankar
  • 3,341
  • 2
  • 20
  • 37