本节课程将学习以下两个练习:
- 练习1:打印100~200之间的所有素数。
- 练习2:用
*
在命令行中打印出金字塔图案。
目标:熟悉Java语言中的for循环的使用方法。
练习1
源码:(请动手)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16public class Demo01 {
public static void main(String[] args) {
for(int i = 100; i < 201; i++){
boolean b = false;
for(int j = 2; j < i - 1; j++){
int k = i % j;
if(k == 0){
b = true;
}
}
if(!b){
System.out.println(i);
}
}
}
}
作业1:请优化Demo01,提高程序效率。
练习2
源码:(请动手)1
2
3
4
5
6
7
8
9
10
11
12
13public class Demo02 {
public static void main(String[] args) {
for(int i = 1; i < 5; i++){
for (int j = 0; j < 4 - i; j++) {
System.out.print(" ");
}
for (int k = 0; k < i; k++) {
System.out.println("* ");
}
System.out.println("");
}
}
}
作业2:如果要求大家编写一个程序,可以打印出任意行的金字塔图案,应该怎么做呢?


