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("]");
}
4
  • 2
    you can print all elements except the last one and then print the last element seperately Commented Apr 12, 2017 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 ", ". Commented Apr 12, 2017 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. Commented Apr 12, 2017 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 Commented Apr 12, 2017 at 23:06

3 Answers 3

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("]");
}
Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't work
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();
   }
}

5 Comments

Note; rather confusingly, instead of just printing the array OP's code also initialises it.
Oh, OP's code. Yeah that's kinda weird.
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.
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.
Yeah, sorry about that guys, I removed my main method. I thought it would make things easier to read.
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(", "))
  + "]"
);

5 Comments

Collections.asList doesn't work for array of primitive types. You may want to use Stream.of or Arrays.stream instead.
Right, I was thinking of Arrays.asList (no such thing as Collections.asList) while typing it. Hehe :) Thanks! Amended. :)
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<int[]> which will contain one element, array itself. You will not get List<int> (since generic types can't be primitive) nor List<Integer> (since autoboxing applies only for primitive types, but any array is not primitive type, even int[]).
Had to open an IDE to fix it! hehe. Amended! :) Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.