我正在生成一系列用 space 分隔的数字,但我想删除最后的 space

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

我正在使用 for 循环生成一系列数字,用 space 分隔,但我想最后删除尾随 space。无法使用 trim() 作为输出。

 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 这里)

但我想要在 5.

之后没有 space 的输出
int i;
for(i = 1; i < str.length(); i++) {
  System.out.print(i + " ");
}
System.out.println(i);

你想要的逻辑是在每个数字后面打印一个 space,除了最后一个数字。你的代码中应该有这个条件逻辑。喜欢,

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

注意:如果变量包含数字,调用它会很混乱str;每个人都会假设它是一个字符串而不是数字。您可以将代码更改为如下内容:

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(" ");
    }
}

像这样在 for 循环中做一个 if 测试

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