Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print the results of an array in a single line?

Tags:

java

I would like to know if anybody could help me to understand why my array result does not come in one single line. The results of the code below is printed as:

[
1
2
3
4
5
6
7
8
9
10
]

Instead of [1 2 3 4 5 6 7 8 9 10].

Any thoughts on what I am doing wrong to the results not come in on line?

class RangeClass {

    int[] makeRange(int lower, int upper) {
      int arr[] = new int[ (upper - lower) + 1 ];

      for(int i = 0; i < arr.length; i++) {
        arr[i] = lower++;
      }
      return arr;
    }

    public static void main(String arguments[]) {
    int theArray[];
    RangeClass theRange = new RangeClass();

    theArray = theRange.makeRange(1, 10);
    System.out.println("The array: [ ");
    for(int i = 0; i< theArray.length; i++) {
      System.out.println(" " + theArray[i] + " ");
    }
    System.out.println("]");
    }
}   
like image 462
Cleiton Lima Avatar asked May 15 '13 12:05

Cleiton Lima


2 Answers

You can use shorter version:

int theArray[] = {1, 2, 3};
System.out.println(java.util.Arrays.toString(theArray));
like image 178
Adam Stelmaszczyk Avatar answered Sep 24 '22 00:09

Adam Stelmaszczyk


Replace System.out.println by System.out.print like this:

System.out.print("The array: [ ");
for(int i = 0; i< theArray.length; i++) {
  System.out.print(" " + theArray[i] + " ");
}
System.out.println("]");

println add a line separator at the end of what you just printed.

like image 32
DeadlyJesus Avatar answered Sep 23 '22 00:09

DeadlyJesus