练习一:打印九九乘法表
public class PrintTest{
public static void main(String[] args){
for(int i = 1;i < 10 ;i++){
for(int j = 1;j <=i ;j++){
System.out.print(j+"*"+i+"="+i*j+"\t");
}
System.out.println();
}
}
}
打印结果:
练习二:打印出100000以内的质数
public static void main(String[] args){
int count = 0;
label:for(int i = 2;i<=100000;i++){
// 2到Math.sqrt(i)之间的数整除代表当前i不是质数
for(int j = 2;j<=Math.sqrt(i);j++){
if(i % j ==0){
//使用带标签的continue 当i被j整除时跳过 count++ 来统计质数的数量
continue label;
}
}
count++;
}
System.out.println(count);
}
打印结果:9592
练习三:打印出菱形
public class PrintPrime {
public static void main(String[] args) {
int length = 5;
//打印上半部分的等腰三角形
for (int i = 0; i < length; i++) {
for (int j = 0; j < length - i; j++) {
System.out.print(" ");
}
for(int k = 0;k<=i;k++) {
System.out.print(" *");
}
System.out.println();
}
//打印下半部分的等腰三角形
for (int i = 0; i < length -1; i++) {
for (int j = 0; j <=i+1; j++) {
System.out.print(" ");
}
for(int k = 0;k<length - i -1;k++) {
System.out.print(" *");
}
System.out.println();
}
}
}
打印结果: