我需要使用以下代码制作一个包含两列的二维表。
public static void printCommonLogTable() {
double x = 0.0;
int i = 1;
while (x <= 10.0) {
System.out.print(x + " " + Math.log(x) + " ");
x = x + 0.5; }
System.out.println("");
}
public static void main(String[] args) {
printCommonLogTable();
}
表格中的第一列应该是您正在计算对数的数字,第二列应该是结果。
但是当我运行这个时,一切都在同一条线上。
最佳答案
那是因为您对 System.out.println("");
的调用放错了位置:它应该位于 while
循环的末尾(但在其内部)。当代码正确缩进时,更容易看到,如下所示:
public static void printCommonLogTable() {
double x = 0.0;
while (x <= 10.0) {
System.out.print(x + " " + Math.log(x) + " ");
x = x + 0.5;
System.out.println();
}
}
请注意,我删除了未使用的 i
变量,并将 System.out.println("");
替换为 System.out.println();
您还可以将两个打印语句合并为一个:
public static void printCommonLogTable() {
double x = 0.0;
while (x <= 10.0) {
System.out.println(x + " " + Math.log(x) + " ");
x = x + 0.5;
}
}
关于Java二维表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33040158/