0

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 :)

qwwdfsad
  • 3,077
  • 17
  • 25
A Madridista
  • 73
  • 1
  • 10
  • Possible duplicate of [trim whitespace from a string?](http://stackoverflow.com/questions/3796121/trim-whitespace-from-a-string) – Rabbit Guy May 05 '16 at 15:58
  • If you're going to write a `for` loop without braces, at least indent the body of the loop so people reading have a chance at guessing what you're trying to do. – khelwood May 05 '16 at 15:58
  • 3
    If you implemented the Collection interface, this would become as easy as `System.out.println( myvector.stream().collect( Collectors.joining(" ")) );`. – Andy Thomas May 05 '16 at 16:04

3 Answers3

3
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.

saml
  • 794
  • 1
  • 9
  • 20
  • 1
    Your welcome though take note of Andy Thomas' solution above using Java 8 and the Collections interface which is much nicer! – saml May 05 '16 at 16:05
2

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();
}
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
2

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]);
urag
  • 1,228
  • 9
  • 28