1206yaya
1/25/2016 - 2:45 AM

コマンドプロンプト上にピラミッドを描く

コマンドプロンプト上にピラミッドを描く

public class Pyramid{
	public static void main(String[] args){
		int height = 0;
		// 入力処理
		try{
			BufferedReader bfReader = new BufferedReader(new InputStreamReader(System.in));
			System.out.println("高さを入力してください。");
			height = checkValidate( bfReader.readLine());
			bfReader.close();
		} catch (NumberFormatException e) {
			System.out.println("引数を整数で入力してください。");
			System.exit(-1); // プログラムを終了
		} catch (IOException e){
			System.out.println("引数を整数で入力してください。");
		}

		int count = height;
		for(int row = 1; row <= count; row++){
			// 空白を表示する
			for(int i = 1; i <= count - row; i++){
				System.out.print(" ");
			}
			// *を表示する
			for(int i = 1; i <= ((row - 1)*2 + 1); i++){
				System.out.print("*");
			}
			// 空白を表示する
			for(int i = 1; i <= count - row; i++){
				System.out.print(" ");
			}
			System.out.println();
		}



	}
	/** valueがnullでない、もしくは正数でない、ならばNumberFormatExceptionを投げる
	* @param value
	* @return result
	*/
	private static int checkValidate(String value) throws NumberFormatException{
		int result=0;
		if(value != null){
			if(Integer.parseInt(value) > 0){
				result = Integer.parseInt(value);
			}else{
				throw new NumberFormatException();
			}
		}
		return result;
	}
}