gpt4 book ai didi

java - 与嵌套 for 循环的斗争

转载 作者:行者123 更新时间:2023-12-02 09:04:24 25 4
gpt4 key购买 nike

我的代码有问题。
我的代码的目标是让用户输入一个数字,然后用于形成乘法表。
例如,如果用户输入数字 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();
}

关于java - 与嵌套 for 循环的斗争,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59933359/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com