1、Java 实例 – 打印菱形:输出指定行数的菱形。
public class Img_Diamond {
public Img_Diamond(){
print(4);
}
public static void print(int size) {
if (size %2 ==0) {
size++;// 计算菱形大小
}
for (int i =0; i < size /2 +1; i++) {
for (int j = size /2 +1; j > i +1; j--) {
System.out.print(" ");// 输出左上角位置的空白
}
for (int j =0; j <2 * i +1; j++) {
System.out.print("*");// 输出菱形上半部边缘
}
System.out.println();// 换行
}
for (int i = size /2 +1; i < size; i++) {
for (int j =0; j < i - size /2; j++) {
System.out.print(" ");// 输出菱形左下角空白
}
for (int j =0; j <2 * size -1 -2 * i; j++) {
System.out.print("*");// 输出菱形下半部边缘
}
System.out.println();// 换行
}
}
}
运行结果:
2、Java 实例 – 九九乘法表:
public class Img_MultiplicationTable {
public Img_MultiplicationTable(){
for(int i=1;i<=9;i++) {
for(int j=1;j<=i;j++) {
System.out.print(j+"×"+i+"="+i*j+"\t");// \t 跳到下一个TAB位置
}
System.out.println();
}
}
}
运行结果:
3、Java 实例 – 打印三角形:
public class Img_Delta {
public Img_Delta(){
for(int i=1;i<=5;i++){
for(int j=5; i<=j; j--)
System.out.print(" ");
for(int j=1; j<=i; j++)
System.out.print("*");
for(int j=1; j
System.out.print("*");
System.out.println();
}
}
}
运行结果:
4、Java 实例 – 打印倒立的三角形:
public class Img_DefaultDelta {
public Img_DefaultDelta(){
//打印倒立的三角形
for (int m =1; m <=4; m++) {
//打印空格
for (int n =0; n <= m; n++) {
System.out.print(" ");
}
//打印*
for (int x =1; x <=7 -2 * (m -1); x++) {
System.out.print("*");
}
System.out.println();
}
}
}
运行结果:
5、Java 实例 – 打印平行四边形:
public class Img_Parallelogram {
public Img_Parallelogram(){
//外层循环 每次打出一个*
for (int i =1; i <=5; i++) {
//填充空格
for (int j =1; j <=5 - i; j++) {
System.out.print(" ");
}
//内层循环 每次打印一个*
for (int k =1; k <=5; k++) {
System.out.print("*");
}
System.out.println();
}
}
}
运行结果:
6、Java 实例 – 打印矩形:
public class Img_Rectangle {
public Img_Rectangle(){
//外层循环 每次输出一行*
for (int i =1; i <=5; i++) {
System.out.print("*");
//内层循环 每次输出一个*
for (int j =1; j <=5; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
运行结果:
网友评论