1. 程式人生 > >java基礎案例---用方法把大象裝進冰箱

java基礎案例---用方法把大象裝進冰箱

程式碼塊:

package com.kdm.ep;

/**
 * 
 * @author cherry.chen
 *
 */
public class Sys3 {
	
	public static void main(String[] args) {
		System.out.println("大象工程---啟動");
		System.out.println("初始化大象和冰箱");
		String[] eps = initElephants(2);
		String fridge = initFridge();

		//大象PK,返回勝利者
		System.out.println("大象PK,返回勝利者");
		String winE =gussingPK(eps[0],eps[1]);
		
		System.out.println("開門,進入冰箱,關門");
		openDoor(winE);
		putElephant(winE,fridge);
		closeDoor(fridge);
	}
	
	//大象PK
	static String gussingPK(String elephantA,String elephantB){
		String winE = null;
		do {
			int gussingNumA = (int) (Math.random() * 3 + 1);
			int gussingNumB = (int) (Math.random() * 3 + 1);
			//System.out.println(gussingNumA + " PK " + gussingNumB);

			// PK
			// 知道數字對應的名稱
			String gNameA = null;
			String gNameB = null;

			gNameA = getNumName(gussingNumA);
			gNameB = getNumName(gussingNumB);
			

			System.out.println(elephantA + "-" + gNameA + " PK " + elephantB + "-" + gNameB);

			// PK:邏輯
			if (gussingNumA == 1 & gussingNumB == 2 || gussingNumA == 2 & gussingNumB == 3) {
				System.out.println(elephantA + "贏啦");
				winE = elephantA;
			} else if (gussingNumA == gussingNumB) {
				System.out.println("平局");
			} else {
				System.out.println(elephantB + "贏啦");
				winE = elephantB;
			}
		} while (winE == null);
		
		//返回勝利者 
		return winE;
	}

	//得到數字對應的文字
	static String getNumName(int num){
		String name = null;
		switch (num) {
		case 1:
			// System.out.println("石頭");
			name = "石頭";
			break;
		case 2:
			// System.out.println("剪刀");
			name = "剪刀";
			break;
		case 3:
			// System.out.println("布");
			name = "布";
			break;
			
		default:
			System.out.println("錯誤!");
			break;
		}
		
		return name;
	}
	
	//初始化大象和冰箱
	static String[] initElephants(int eNum){
		if(eNum <1 || eNum>10){
			System.out.println("數量錯誤");
			return null;
		}
		String[] eps = new String[eNum];
		System.out.print("來了" + eNum + "大象:");
		for(int i =0 ; i <eps.length;i++){
			eps[i] = "大象" + (i+1);
			if(i==eps.length-1){
				System.out.println(eps[i]);
			} else {
				System.out.println(eps[i] + ",");
			}
			
		}
		return eps;
	}
	
    static String initFridge(){
		String fridge = "無敵小冰箱007";
		System.out.println("來了個冰箱" + fridge);
		return fridge;
	}
	
	//大象PK,分出勝負
	
	//冰箱門開啟
	static void openDoor(String fridge){
		System.out.println("冰箱" + fridge + "門開啦");
	}
	
	//大象進入冰箱
	static void putElephant(String elephant,String fridge){
		System.out.println("大象" + elephant +"進入冰箱" +fridge);
	}
	
	//冰箱門關閉
	static void closeDoor(String fridge){
		System.out.println("冰箱" + fridge + "關閉啦");
	}

	
}