java编程 倒金字塔_java打印正金字塔,倒金字塔和“水影”金字塔

本文介绍了如何使用Java编程实现正金字塔、倒金字塔和菱形金字塔的打印。通过用户输入行数,程序动态生成相应形状,并提供错误检查以确保输入的有效性。
摘要由CSDN通过智能技术生成

package com.javase.demo;

import java.util.Scanner;

/**

* 金字塔

* @author Mr.Zhang

*

*/

public class Pyramid {

static Scanner input = new Scanner(System.in);

/**

* *****打印金字塔*****

* 1,确定金字塔行数

* 2,确认空格数

* 3,确认星星数

* @param args

*/

public static void main(String[] args) {

entrance();

}

/**

* 入口项

*/

public static void entrance() {

System.out.println("请选择(0--正金字塔,1--倒金字塔,2--菱形金字塔)");

String select = input.nextLine();

if(isNumber(select)){

int selectInt = Integer.parseInt(select);

switch(selectInt){

case 0:

uprightPyramid();

break;

case 1:

fallPyramid();

break;

case 2:

System.out.println("该功能尚未完善!");

break;

default:

System.out.println("请输入正确的选项!");

entrance();

break;

}

}else if(!select.equals(0) || !select.equals(1) || !select.equals(2)){

nullSuccess();

}

}

/**

* 打印正金字塔

* @param input

*/

public static void uprightPyramid() {

System.out.println("请输入行数:");

String row = input.nextLine();

if(isNumber(row)){

int rows = Integer.parseInt(row);

for(int i = 1;i <= rows;i++){ //循环输入的行数,

for(int j = 1;j <= rows - i;j++){ //输出循环每行的空格

System.out.print(" ");

}

for(int k = 1;k <= 2 * i - 1;k++){ // 输出循环每行的★

System.out.print("★");

}

System.out.println();

}

System.out.println("打印完成,线程结束");

}else{

nullSuccess();

}

}

/**

* 打印倒金字塔

*/

public static void fallPyramid(){

System.out.println("请输入行数:");

String row = input.nextLine();

if(isNumber(row)){

int rows = Integer.parseInt(row);

for(int i = rows;i >= 1;i--){

for(int j = 0;j < rows-i;j++){ //打印空格数

System.out.print(" ");

}

for(int k = 0;k < i * 2 - 1;k++){ //打印★数

System.out.print("★");

}

System.out.println();

}

System.out.println("打印完成,线程结束");

}else{

nullSuccess();

}

}

/**

* 判断是否为数字

* @param str

* @return

*/

public static boolean isNumber(String str){

boolean ok = false;

if(null != str && str.matches("^[0-9]")){

return true;

}

return ok;

}

/**

* 调用错误结果

*/

public static void nullSuccess(){

System.out.println("您输入的不是数字,一遍浪去,不听话的孩子!");

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值