for循环之打印N行菱形

 
package com.accp.ch1;

import java.util.Scanner;

/**
 * 编写JAVA程序,实现使用“*”打印输出菱形
 * @author wuhao
 *
 */
public class DiamShape {
	public static void main(String[] args) {
		while(true){
			Scanner sc = new Scanner(System.in);
			System.out.println("请输入您想到打印的菱形的行数,然后回车确认(注:数字只能是大于0的整数!)");
			System.out.print("请输入:");
			int lineSize = sc.nextInt();
			System.out.println("------------------------");
			new PrintDiamond(lineSize);//要打印的菱形的行数!
			System.out.println("------------------------");
		}
	}
}

class PrintDiamond{
	private int lineSize;//菱形总共占的行数,注:只能是单数!
	public PrintDiamond(int max){
		if(max < 0){
			System.out.println("您输入的数据不合法:必须是大于0的整数!");
			return;
		}else if(max % 2 == 0){
			System.out.println("您输入的如果是偶数,将会自动加1再输出!");
			this.lineSize = max + 1;
		}else{
			this.lineSize = max;
		}
		//mid为最中间是第几行(行号)!
		//比如输出图形为9行的菱形,中间行就是第5行,mid就是5;
		int mid = (lineSize + 1) / 2;
		for(int i = 1; i <= lineSize; i++){
			int j,k;
			if(i <= mid){
				for(j = 1; j <= mid - i; j++){
					System.out.print(" ");
				}
				for(k = 1; k <= 2 * i - 1; k++){
					System.out.print("*");
				}
			}else{
				for(j = 1; j <= i - mid; j++){
					System.out.print(" ");
				}
				for(k = 1; k <= lineSize - 2 * (j -1); k++){
					System.out.print("*");
				}
			}
			System.out.println();
		}
	}
}

你可能感兴趣的:(习题)