循环结构是Java中最重要的控制结构之一。它允许你多次执行相同的代码块,同时也提供了一些可用于控制循环行为的关键字。
以下是一些练习题,可以帮助你加强对Java循环的理解:
for(int i=1; i<=10; i++){ for(int j=1; j<=10; j++){ System.out.print(i*j + "\t"); } System.out.println(); }
int rows = 10; int[] currentRow = {1}; for(int i=0; i<rows; i++){ for(int j=0; j<currentRow.length; j++){ System.out.print(currentRow[j] + " "); } System.out.println(); int[] newRow = new int[currentRow.length+1]; newRow[0] = 1; newRow[newRow.length-1] = 1; for(int j=1; j<newRow.length-1; j++){ newRow[j] = currentRow[j-1] + currentRow[j]; } currentRow = newRow; }
int sum = 0; for(int i=2; i<=100; i+=2){ sum += i; } System.out.println("The sum of even numbers from 1 to 100 is " + sum);
int number = 47; boolean isPrime = true; for(int i=2; i<number; i++){ if(number%i == 0){ isPrime = false; break; } } if(isPrime){ System.out.println(number + " is a prime number"); } else { System.out.println(number + " is not a prime number"); }
int n = 5; for(int i=1; i<=n; i++){ for(int j=1; j<=i; j++){ System.out.print("* "); } System.out.println(); }
以上练习题可以帮助你熟悉和加强对Java循环的理解。
原文链接:codingdict.net