3

好的,我正在为我的编程课程制作一个程序,我正在尝试获取它,所以当我输入列和行时,它会得到一个显示乘法表的输出。下面是一个可视化的示例: printTable(4,6) 的示例运行输出:

例子:

现在,这是我的代码:

 import java.util.Scanner;

 public class Pictures {

public static int row;
public static int column;
public static Scanner input = new Scanner(System.in);

public static void main(String[] args){
int x = 1;
int y = 1;

System.out.println("Input Row: ");
row = input.nextInt();
System.out.println("Input Column: ");
column = input.nextInt();

for(x = 1; x < row; x++){
    System.out.print(x * y +  "    ");

    for(y = 1 ; y < column; y++){

        System.out.print(y * x + "    ");
    }
    System.out.println();   
}   
}
}

现在,当我输入第 5 行和第 5 列时,我的输出如下所示:

1    1    2    3    4    
10    2    4    6    8    
15    3    6    9    12    
20    4    8    12    16

我知道我没有看到一些相当简单的东西,但我就是不明白为什么会这样。如果有人可以提供建议,那将有很大帮助。

谢谢,萨利

4

5 回答 5

4

出于学习目的,请使用调试器来理解您的代码。

要修复它,请删除这些行:

int x = 1;
int y = 1;

并让你的循环像:

for(int x = 1; x < row; x++){
    // System.out.print(x * y +  "    "); // no print needed here
    for(int y = 1 ; y < column; y++){
        System.out.print(y * x + "\t");
    }
    System.out.println(); 
}  

这是Oracle Java 教程中解释循环的部分的链接。for感谢迈克在评论中提到均匀间距。更新了代码。

于 2013-01-04T20:44:51.403 回答
0

当你做

System.out.print(x * y + " ");

第二次,由于 for 循环,y = 5。因此 2 * 5 = 10。

于 2013-01-04T20:42:32.740 回答
0

如果你想得到 4 行,你想显示行、1、2、3 和 4。如果你在 < 4(而不是 <= 4)处停止循环,你会错过最后一行和最后一列。这就是人们所说的栅栏错误

尝试这样的事情:

for(int x = 1; x <= row; x++)

此外,您还没有很好的 y 值。您希望 x 和 y 都有效,因此只能在内循环内打印。

于 2013-01-04T20:46:17.500 回答
0
for(x = 1; x < row; x++){
    System.out.print(x * y +  "    ");
    for(y = 1 ; y < column; y++){
        System.out.print(y * x + "    ");
    }
    System.out.println();   
}   

第一个 print() 是不需要的,您需要更改比较,使得rowcolumn分别是 x 和 y 的有效值(即使用<=而不是<。此外,您将希望使用"\t"(制表符)隔开列,而不是" ", 这样不同位数的数字就不会导致列倾斜。这应该会产生预期的结果。

for(x = 1; x <= row; x++){
    for(y = 1 ; y <= column; y++){
        System.out.print(y * x + "\t");
    }
    System.out.println();   
}   

输出 4,6 与" "...

1    2    3    4    5    6    
2    4    6    8    10    12    
3    6    9    12    15    18    
4    8    12    16    20    24    

输出 4,6 与"\t"...

1   2   3   4   5   6   
2   4   6   8   10  12  
3   6   9   12  15  18  
4   8   12  16  20  24  
于 2013-01-04T20:46:29.310 回答
-2

第一个print是错误的,因为它使用了y前一个 for 循环中的值。

将其更改为:

for(x = 1; x <= row; x++){
  System.out.print(x +  "    ");
  for(y = 1 ; y <= column; y++){
    System.out.print(y * x + "    ");
  }
  System.out.println();
}

更新:循环结束也是<,而它们应该是<=(因为它们是基于 1 的)。我在上面的片段中更新了它。

于 2013-01-04T20:42:47.187 回答