A Madridista
A Madridista

Reputation: 73

JAVA deleting the first whitespace of arraylist

i got this code : and i want to Display each element in the vector seperated by a space.

public void display() {
    for(int i = 0; i < length; i++) {
    System.out.print(" "+this.elements[i]);
    }
    System.out.println();
}

i am getting all the elements with a space between each element, BUT HOW CAN I GET RID OF THE WHITE SPACE AT THE BEGINNING OF THE LINE ??

and im not sure if theres something to do with the VECTOR CLASS, thats the beginning of my code:

public class Vector {

private Long sum;
private Long mode;
private Long median;
private Long minimum;
private Long maximum;

private final int length;
private final long[] elements;


public Vector(int length) {

    this.sum = null;
    this.mode = null;
    this.median = null;
    this.minimum = null;
    this.maximum = null;

    this.length = length;
    this.elements = new long[length];

    }

the code is a bit long, so i hope i can get some help from what i have posted thank you :)

Upvotes: 0

Views: 54

Answers (3)

saml
saml

Reputation: 794

public void display() {
    for(int i = 0; i < length; i++){
    if(i > 0){ 
      System.out.print(" ");
    }
    System.out.print(this.elements[i]);
   }
   System.out.println();
}

This should do it - it will only print a space if its the second or greater element.

Upvotes: 3

urag
urag

Reputation: 1258

You getting white space because you start printing with white space simplest solution is to use

    System.out.print(this.elements[i] + " ");

instead of

    System.out.print(" "+this.elements[i]);

Upvotes: 2

Nicolas Filotto
Nicolas Filotto

Reputation: 44965

By checking if the current element is not the first one like this:

public void display() {
    for(int i = 0; i < length; i++) {
        if (i > 0) {
            System.out.print(' ');
        }           
        System.out.print(this.elements[i]);
    }
    System.out.println();
}

Upvotes: 2

Related Questions