[英]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.