6

guys I was wondering how to remove the extra comma and space from the array? When I run the program it gives me {1, 2, 3, 4, 5, }. What I want is {1, 2, 3, 4, 5}. Main must stay the same. PrintArray method is the one I need help with.

Referring to duplicate question statement. This is different because it asks a user for a number and prints the array accordingly. This is not a duplicate question.

public static void printArray(int[] myArray) {
    System.out.print("[");
    for(int i = 0; i < myArray.length; i++) {
        myArray[i] = i + 1;
        System.out.print(myArray[i] + ", ");
    }

    System.out.println("]");
}
0009laH
  • 1,960
  • 13
  • 27
IDK
  • 119
  • 1
  • 1
  • 8
  • 2
    you can print all elements except the last one and then print the last element seperately – Meccano Apr 12 '17 at 22:29
  • truncate the last 3 characters and then append "]" back. Or better yet, instead of blindly appending the `", "`, check the length of `myArray` and the value of `i` to determine if you need to append `", "`. – WOUNDEDStevenJones Apr 12 '17 at 22:29
  • 1
    I also sometimes build the output in a `StringBuilder`, then just always remove the last space and comma. `StringBuilder` is just a `char[]` under the hood, so removing two characters from the end is easy. The resulting code is pretty compact and efficient too. – markspace Apr 12 '17 at 22:37
  • To avoid confusion, I suggest your `printArray` method, only print the array. Having it also initialise the array is a confusing complication missed by some answering the question. You could call the method `initialiseAndPrintArray` – Peter Lawrey Apr 12 '17 at 23:06

3 Answers3

9

Don't print it in the first place. Print the comma before the string and only when i > 0.

public static void printArray(int[] myArray)
{

    System.out.print("[");
    for(int i = 0; i < myArray.length; i++)
    {
        myArray[i] = i + 1;
        if (i > 0)
        {
            System.out.print(", ");
        }
        System.out.print(myArray[i]);
    }
    System.out.println("]");
}
John3136
  • 28,809
  • 4
  • 51
  • 69
6

The easy way to do this is just use Arrays.toString

public static void printArray(int[] myArray)
{
    System.out.print( Arrays.toString( myArray ) );
}

Note this prints brackets instead of braces. In the interest of completeness, if you do implement this yourself, don't forget to check for the array being null in addition to other boundary conditions like length = 0.

Here is an example using StringBuilder, where I just always remove the last two characters after checking for null and length = 0. If you have a very complicated string to calculate for each item in a list/array, this can be easier than copying the code to make each item outside the loop, and can be slightly faster than checking for i==array.length-1 each time through the loop.

public class MyArraysToString
{

   public static void main( String[] args )
   {
      int[] test = { 8, 7, 6, 5, 4, };
      printArray( test );
      System.out.println( myToString( null ) );
      System.out.println( myToString( new int[0] ) );
      System.out.println( myToString( test ) );
   }

   public static void printArray( int[] myArray )
   {
      System.out.println( Arrays.toString( myArray ) );
   }

   public static String myToString( int[] a ) {
      if( a == null ) return "null";
      if( a.length == 0 ) return "{}";
      StringBuilder sb = new StringBuilder();
      sb.append( '{' );
      for (int i = 0; i < a.length; i++) {
         sb.append( a[i] );
         sb.append( ", " );
      }
      sb.setLength( sb.length()-2 );
      sb.append( '}' );
      return sb.toString();
   }
}
markspace
  • 10,621
  • 3
  • 25
  • 39
  • Note; rather confusingly, instead of just printing the array OP's code also initialises it. – Peter Lawrey Apr 12 '17 at 23:02
  • Oh, OP's code. Yeah that's kinda weird. – markspace Apr 12 '17 at 23:03
  • The original code has `myArray[i] = i + 1;` which is going to do something different from your code. IMHO your code makes more sense, it just doesn't do the same thing. – Peter Lawrey Apr 12 '17 at 23:05
  • 1
    I assume that was just a test case so he could produce output, but yeah he might have meant to also initialize the array too, in which case his question doesn't really match his problem. – markspace Apr 12 '17 at 23:06
  • Yeah, sorry about that guys, I removed my main method. I thought it would make things easier to read. – IDK Apr 13 '17 at 23:51
4

I would modify it as such (printing the comma before the next item, for index > 0)

System.out.print("[");
for(int i = 0; i < myArray.length; i++) {
  myArray[i] = i + 1;
  System.out.print(((i > 0) ? ", " : "") + myArray[i]);
}
System.out.print("]");

Or, in Java 8,

System.out.println(
  "[" + 
  Arrays.stream(array)
      .mapToObj(String::valueOf)
      .collect(Collectors.joining(", "))
  + "]"
);
Gabe
  • 431
  • 3
  • 11
  • `Collections.asList` doesn't work for array of primitive types. You may want to use `Stream.of` or `Arrays.stream` instead. – Pshemo Apr 12 '17 at 22:34
  • Right, I was thinking of `Arrays.asList` (no such thing as `Collections.asList`) while typing it. Hehe :) Thanks! Amended. :) – Gabe Apr 12 '17 at 22:37
  • Actually I also was thinking about `Arrays.asList` so problem stays. Take a look. If you have `int[] array = {1,2}` and you use `Arrays.asList` you will get `List` which will contain one element, array itself. You will not get `List` (since generic types can't be primitive) nor `List` (since autoboxing applies only for primitive types, but *any* array is not primitive type, even `int[]`). – Pshemo Apr 12 '17 at 22:41
  • Take a look at [Arrays.asList() not working as it should?](http://stackoverflow.com/questions/1467913/arrays-aslist-not-working-as-it-should), especially this answer: http://stackoverflow.com/a/1467940/1393766 – Pshemo Apr 12 '17 at 22:48
  • Had to open an IDE to fix it! hehe. Amended! :) Thanks! – Gabe Apr 12 '17 at 22:49