可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
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 –