2014-10-19 30 views
2

我是Java新手。我试图做一个三角形的乘法表看起来有点像这样:三角乘法表

输入行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 

每一行/列的#有编号的,我不知道如何做到这一点。我的代码看起来好像没有了,因为我得到了一个无限循环,它没有包含正确的值。下面你会发现我的代码。

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是指应该正确格式化图表的外部文件,所以忽略它。如果有人可以请指点我正确的方向,至于修复我现有的代码并添加代码来对列和行进行编号,那将不胜感激!

回答

0

两个嵌套的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(); 
} 

输出

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 
+0

太感谢你了,伙计!这正是我需要的。我怎样才能让列被编号? :) – Blackout621 2014-10-19 03:13:28

+0

首先打印一个(在循环中):'System.out.printf(“%d \ t”,i);'1-7之间。我会将其添加到答案中。 – alfasin 2014-10-19 03:15:36

+0

完美的工作!再次,谢谢你。这个程序在过去的一个多小时里我一直在努力挣扎。 – Blackout621 2014-10-19 03:21:20