学习Java第五天--循环结构之课堂案例

使用循环结构打印等腰三角形、菱形、ATM服务界面

课堂案例

1. 打印等腰三角形

public class TestNested{
	public static void main(String[] args){
		//打印等腰三角形
		//####*
		//###***
		//##*****
		//#*******
		//*********
		int rows = 5;
		for(int i = 1;i <= rows;i++){//外层打印5行
			for(int j = rows - 1;j >= i;j--){//打印4行的直角三角形
				System.out.print(" ");
			}
			for(int j = 1;j <= 2 * i - 1;j++){//打印5行的等腰三角形
				System.out.print("*");
			}
			System.out.println();
		}
		//打印正的直角三角形(每次递进数值上 *2-1)
		//*
		//***
		//*****
		//*******
		//*********
		for(int i = 1;i <= rows;i++){
			for(int j = 1;j <= 2 * i - 1;j++){
				System.out.print("*");
			}
			System.out.println();
		}
	}
}

2. 打印菱形

import java.util.Scanner;
public class TestNested2{
	public static void main(String[] args){
		//菱形
		//####*
		//###***
		//##*****
		//#*******
		//*********			
		//#*******
		//##*****
		//###***
		//####*
		//菱形必须是奇数行数
		//控制台输入一个行数,如果行数合法,向下执行;如果不合法,则让用户重新输入
		Scanner input = new Scanner(System.in);
		int rows;
		do{
			System.out.println("请输入菱形行数(奇数):");
			rows = input.nextInt();
		}while(rows % 2 == 0);
		//打印菱形
		int up = rows / 2 + 1;		//将菱形分为上下两部分打印
		int down = rows / 2;
		for(int i = 1;i <= up;i++){//打印菱形上半部
			for(int j = up - 1;j >= i;j--){//打印倒直角三角形空格占位
				System.out.print(" ");
			}
			for(int j = 1;j <= 2 * i - 1;j++){//打印正等腰三角形
				System.out.print("*");
			}
			System.out.println();
		}
		for(int i = 1;i <= down;i++){//打印菱形下半部
			for(int j = 1;j <= i;j++){//打印正直角三角形空格占位
				System.out.print(" ");
			}
			for(int j = 2 * down - 1;j >= 2 * i - 1;j--){//打印倒等腰三角形
				System.out.print("*");
			}
			System.out.println();
		}
	}
}

3. ATM服务界面

import java.util.Scanner;
public class TestBankMenu{
	public static void main(String[] args){
		//ATM菜单
		Scanner input = new Scanner(System.in);
		int choice;
		int flag = 0;
		do{
			System.out.println("=================欢迎使用ATM自动银行服务================");
			System.out.println("1.开户 2.存款 3.取款 4.转账 5.查询余额 6.修改密码 0.退出");
			System.out.println("========================================================");
			System.out.print("请输入操作编号:");
			choice = input.nextInt();
			switch(choice){
				case 1:
					System.out.println("==执行开户功能==");
					break;
				case 2:
					System.out.println("==执行存款功能==");
					break;
				case 3:
					System.out.println("==执行取款功能==");
					break;
				case 4:
					System.out.println("==执行转账功能==");
					break;
				case 5:
					System.out.println("==执行查询余额功能==");
					break;
				case 6:
					System.out.println("==执行修改密码功能==");
					break;
				case 0:
					System.out.println("==执行退出功能==");
					break;
				default:
					flag++;
					if(flag == 3){
						break;
					}
					System.out.println("==输入错误,请重新输入!==\n");
					break;
			}
			if(flag == 3){
				System.out.println("\n==输入错误3次,程序结束==");
				break;
			}
		}while(choice < 0 || choice > 6);
	}
}
发布了34 篇原创文章 · 获赞 7 · 访问量 1315

猜你喜欢

转载自blog.csdn.net/weixin_44257082/article/details/104229018