【发布时间】:2014-11-05 01:37:59
【问题描述】:
我在下面编写了这个程序,用于打印从 1 到 12 的乘法表。我还想在由几个空格和“|”分隔的一侧打印 1 到 12。我设置了一个 if-else 语句来减少所需的空格数,具体取决于该数字中有多少位,但是当我运行下面的代码时,它会打印出前两行,然后停止。
也许我今天盯着代码看太久了,但我一辈子都想不通它为什么会这样。
顺便说一句,当我删除最后的 if-else 语句并且只有“System.out.println(print);”时,表格本身打印得很好在嵌套的 for 循环之后。
import java.util.*;
public class MultiplicationTable{
public static void main(String[] args){
int n = 12;
int temp;
int length;
String[][] table = new String[n][n];
/**Assign values to the array*/
/**These are the rows*/
for(int i = 1; i <= n; i++){
/**These are the columns*/
for(int j = 1; j <= n; j++){
/**this is the current multiplication value*/
temp = i*j;
/**assigning the value to it's place in the array*/
table[i-1][j-1] = String.valueOf(temp);
/**determining how many spaces are required to keep the table ordered*/
length = String.valueOf(temp).length();
if(length==1){
table[i-1][j-1] = table[i-1][j-1]+" ";
}
else if(length==2){
table[i-1][j-1] = table[i-1][j-1]+" ";
}
else{
table[i-1][j-1] = table[i-1][j-1]+" ";
}
}
}
/**This is to print out the array*/
String print;
for(int x = 0; x<n; x++){
print = "";
for(int y=0; y<n; y++){
print = print + String.valueOf(table[x][y]);
}
/**This is for determining how many spaces are needed in front of the lines*/
length = String.valueOf(x+1).length();
//This is for error testing
System.out.println("");
System.out.println(length);
System.out.println("");
//End of error testing
if(x==1){
System.out.println(x+" |"+print);
}
else if(x==2){
System.out.println(x+" |"+print);
}
}
}
}
【问题讨论】:
-
我不会调试上面的代码来看看这个建议是否有效,但你的
if(x==1)应该是if(length==1)。请学习使用调试器来单步调试您的代码,以便您自己查看流程。 -
啊该死的。谢谢你。你当然是对的。
标签: java arrays if-statement