Search code examples
javafor-looptrim

I am generating a series of numbers delimited with space but I want to remove the space at end


I am generating the series of numbers using for loop, delimited with space but I want to remove trailing space at last. Unable to use trim() for the output.

 import java.util.*;
public class Main {
    public static void main(String [] args){
        Scanner s = new Scanner(System.in);
        int str = s.nextInt();

    for(int i=1; i<=str; i++) {
        System.out.printf("%d", i);
        System.out.print(" ");
    }
    }
}

1 2 3 4 5(space here)

but I want output without the space after 5.


Solution

  • Do an if test inside the for-loop like this

    if (i == str) {
        System.out.printf("%d", i); 
    } else {
        System.out.printf("%d", i); 
        System.out.print(" "); 
    }