0

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.

shantz
  • 25
  • 6
  • 1
    Could you please tell us **why** you are *unable to use `trim()` for the output? What type does your series of numbers have? Is it a `String`? You should really post the code that produces the series here. – deHaar Aug 12 '19 at 11:15
  • Share some code. Otherwire we're not able to help. – M. Prokhorov Aug 12 '19 at 11:16
  • See the code now. Why don't you just not print the last space then? – M. Prokhorov Aug 12 '19 at 11:21
  • use a stringbuilder if you are building strings inside a loop, you can also just remove the last character when you are getting the value of your stringbuilder, and then log the value, don't just push everything to sys/out/print because then you can't interact with the value – Saik Caskey Aug 12 '19 at 11:23
  • Thats what I want to know how to remove it? @M. Prokhorov – shantz Aug 12 '19 at 11:24
  • @ShantanuUdasi, you don't "remove" it. You *don't print it*. – M. Prokhorov Aug 12 '19 at 11:27

3 Answers3

1
int i;
for(i = 1; i < str.length(); i++) {
  System.out.print(i + " ");
}
System.out.println(i);
ILikeSahne
  • 170
  • 2
  • 10
  • While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Popeye Aug 12 '19 at 12:58
0

The logic you want is to print a space behind every number, except for the last number. You should have this conditional logic in your code somewhere. Like,

if (i < str)
    System.out.print(" ");

Note: it's very confusing to call a variable str if it contains a number; everyone will assume that it's a String instead of a number. You could change code to something like this:

public static void main(String [] args){
    Scanner s = new Scanner(System.in);
    int n = s.nextInt();

    for(int i = 1; i <= n; i++) {
        System.out.print(i);
        if (i < n)
            System.out.print(" ");
    }
}
Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
0

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(" "); 
}
Muderino
  • 66
  • 8