Java 与嵌套for循环斗争
我的代码有问题。 我的代码的目标是让用户输入一个数字,然后用于生成表单 乘法表。例如,如果用户输入数字4,则程序应打印以下内容:**Java 与嵌套for循环斗争,java,Java,我的代码有问题。 我的代码的目标是让用户输入一个数字,然后用于生成表单 乘法表。例如,如果用户输入数字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 MultiplicationTa
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++)
并删除循环末尾的分号。删除第二个for循环头后面的分号,并对该循环的两个语句使用大括号。仅供参考,循环是嵌套的,而不是嵌套的:-