简体   繁体   English

三角乘法表

[英]Triangular Multiplication Table

I'm new to Java. 我是Java新手。 I'm trying to make a triangular multiplication table that looks somewhat like this: 我正在尝试制作一个看起来像这样的三角乘法表:

Enter # of rows 7 输入行数7

1   2   3   4   5   6   7
1
2   4
3   6   9
4   8   12  16  
5   10  15  20 25
6   12  18  24 30 36
7   14  21  28 35 42 49

Each row/column has to be numbered, and I have no idea how to do this. 每行/每一列都必须编号,我不知道该怎么做。 My code is seemingly waaay off, as I get an infinite loop that doesn't contain the correct values. 我的代码似乎不正确,因为我遇到了一个不包含正确值的无限循环。 Below you will find my code. 在下面,您将找到我的代码。

public class Prog166g
{
  public static void main(String args[])
   {
    int userInput, num = 1, c, d;
    Scanner in = new Scanner(System.in);

    System.out.print("Enter # of rows "); // user will enter number that will define output's           parameters
    userInput = in.nextInt();

    boolean quit = true;
    while(quit)
    {
        if (userInput > 9)
        {
            break;
        }
        else
        {
        for ( c = 1 ; c <= userInput ; c++ )
        { System.out.println(userInput*c);
          for (d = 1; d <= c; d++) // nested loop required to format numbers and "triangle" shape
          {
                System.out.print(EasyFormat.format(num,5,0));
          }
        }
    }
    }
   quit = false;
   }
} 

EasyFormat refers to an external file that's supposed to format the chart correctly, so ignore that. EasyFormat是指应该正确设置图表格式的外部文件,因此请忽略该文件。 If someone could please point me in the right direction as far as fixing my existing code and adding code to number the columns and rows, that would be greatly appreciated! 如果有人可以向我指出正确的方向,以修复我现有的代码并添加代码以对列和行进行编号,将不胜感激!

Two nested for loops will do the trick: 两个嵌套的for循环可以解决问题:

for (int i = 1; i < 8; i++) {
    System.out.printf("%d\t", i);
}
System.out.println();
for (int i = 1; i < 8; i++) {
    for (int j = 1; j <= i; j++) {
        System.out.printf("%d\t", i * j);
    }
    System.out.println();
}

OUTPUT OUTPUT

1   2   3   4   5   6   7   
1   
2   4   
3   6   9   
4   8   12  16  
5   10  15  20  25  
6   12  18  24  30  36  
7   14  21  28  35  42  49  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM