java from space to space_How to remove space from the end of a line in for loop

可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:

问题:

The problem is the next, at the end of every line, the program writes a space. How to remove it?

public class Szorzotabla {

public static void main(String[] args) {

for (int i = 1; i < 10; i ++) {

for (int j = 1; j < 10; j++) {

System.out.print(i * j + " ");

}

System.out.println();

}

}

}

I expected the output of the multiplication table without space at the end of every line.

回答1:

You can use this way :

String space;

for (int i = 1; i < 10; i ++) {

space = ""; // declare a variable here

for (int j = 1; j < 10; j++) {

System.out.print(space + i * j); // and note here to change the order

space = " "; // after the first iteration set a space to the variable

}

System.out.println();

}

回答2:

There are a couple of ways to solve this. One of the cleaner solutions might be to use Java's built-in ability to join Strings (added in Java 8, if I recall).

for (int i = 1; i < 10; i++) {

String[] products = new String[9];

for (int j = 1; j < 10; j++) {

products[j-1] = String.valueOf(j * i);

}

System.out.println(String.join(" ", products));

}

回答3:

You're getting a space at the end of the line because you're printing a space at the end of every i*j even though you don't need one for the last one of each line.

Instead, you can change it so that you print the space before i*j, and manually print the first i*j without a space before you enter the inner loop. This way your code remains relatively clean.

for(int i = 1; i < 10; i ++) {

System.out.print(i);

for(int j = 2; j < 10; j++) { //start j at 2

System.out.print(" " + i * j);

}

System.out.println();

}

回答4:

How about that:

IntStream.range(1, 10)

.mapToObj(i -> IntStream.range(1, 10)

.mapToObj(j -> i * j).map(Object::toString)

.reduce((s1, s2) -> s1 + " " + s2).get())

.forEach(System.out::println);

回答5:

Solution similar to @Andronicus with stream api:

IntStream.range(1, 10)

.mapToObj(i -> IntStream.range(1, 10)

.mapToObj(j -> String.valueOf(i * j))

.collect(joining(" ")))

.forEach(System.out::println);

回答6:

System.out.print(i * j + ( j < 9 ? " ", "" ));

when j is less than 9 (last) concat space else concat empty –

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值