繁体   English   中英

与嵌套 for 循环的斗争

[英]Struggles with nested for-loop

我的代码有问题。
我的代码的目标是让用户输入一个数字,然后将其用于形成乘法表。
例如,如果用户输入数字 4,程序应该打印以下内容:**

1 * 1 = 1
1 * 2 = 2  2 * 2 = 4 
1 * 3 = 3  2 * 3 = 6  3 * 3 = 9
1 * 4 = 4  2 * 4 = 8  3 * 4 = 12  4 * 4 = 16 

这是我目前的代码。 感谢任何形式的帮助!

import java.util.Scanner;

public class MultiplicationTable {
    public static void main (String[] arg) {

        Scanner gt = new Scanner(System.in); 
        System.out.println("Enter a number for multiplication: ");
        int N = gt.nextInt();

        for(int i = 1; i < N; i++) {
            for(int j = 1; j < N; j++);
                int product = i * j;
                System.out.print(i +" * " +j +" = " +product );
            System.out.println();       
        }   
    }

} 

您的代码中有两个小错误,否则您就可以开始了。

for(int i = 1; i < N; i++) {
    for(int j = 1; j < i; j++); //<-- remove this semicolon
    {   // <-- use curly braces here for the loop statements
        int product = i * j;
        System.out.print(i +" * " +j +" = " +product+" "); //<--add an additional space at the end
    }
    System.out.println();       
}   

要获得金字塔结构,您应该将第二个循环限制更改为 i :

for(int j = 1; j < i; j++)

并删除循环末尾的分号。

暂无
暂无

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

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