我创建了一个乘法表。但是,它无法使用我的代码显示第一行和第一列。这甚至可以通过循环实现吗?先生是我的代码:
int a;
int b;
for (a=1; a<=3; a++)
{
for (b=1; b<=3; b++)
{
System.out.print(a*b + " ");
}
System.out.println();
}
这段代码的输出是:
1 2 3
2 4 6
3 6 9
但是,我希望仅显示行和列上的 123。这是可以实现的吗?
期望的输出:
1 2 3
2
3
一个基本的方法是知道你的外循环在哪里并相应地打印出你想要的结果。
public class StackOverflow {
public static void main(String[] args) {
int a;
int b;
for (a=1; a<=3; a++)
{
// Only print the first row
if (a == 1) {
for (b=1; b<=3; b++)
{
System.out.print(a*b + " ");
}
// Ends the first row
System.out.println("");
} else {
// Prints the rest of the first column
System.out.println(a);
}
}
}
}
结果:
1 2 3
2
3
如果我理解你的评论,这里有一种只有一个循环的方法。它假定行的大小将等于列的大小。这意味着您将显示的位数将是一个奇数(rowColLength * 2 - 1)
,这使得第一个数字成为枢轴点。
public class StackOverflow {
public static void main(String[] args) {
int a = 0;
int rowColLength = 3;
int numberOfDigits = rowColLength * 2 - 1;
for (int i = 0; i < numberOfDigits; i++) {
if (i < rowColLength) {
// Prints the first row
System.out.print(++a + " ");
} else if (i == rowColLength){
// Decrements the last number from the first row
// to continue the column count for printing
System.out.print("\r\n" + --a);
} else {
// Prints the rest of the column
System.out.print("\r\n" + ++a);
}
}
}
}
结果:
1 2 3
2
3
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句