Java编程基础:循环、类与对象的深入解析
1. 嵌套循环
在Java编程中,嵌套循环是一种强大的工具,可用于解决各种编程问题。例如,下面的程序使用嵌套 for
循环来找出2到100之间每个数的因数:
/*
Use nested loops to find factors of numbers
between 2 and 100.
*/
class FindFac {
public static void main(String args[]) {
for(int i=2; i <= 100; i++) {
System.out.print("Factors of " + i + ": ");
for(int j = 2; j < i; j++)
if((i%j) == 0) System.out.print(j + " ");
System.out.println();
}
}
}
该程序的部分输出如下:
Factors of 2:
Factors of 3:
Factors of 4: 2
Factors of 5:
Factors of 6: 2 3
Factors of 7:
Factors of 8: 2 4
Factors of 9: 3
Factors of 10: 2 5
Factors of 11:
Factors of 12: 2 3 4 6
Factors of 13:
Factors of 14: 2 7
Factors