傳智播客 java基礎 相關資料 Day1

SieSteven發表於2017-06-07
package chuanzhiboke;

import java.util.Scanner;
/**
 * 2017-6-7 
 * 主題:分支語句練習。switch  if 實現分支
 * 零散點:
 * 		0、靜態只讀的宣告語法  static final ****  ***=***; 集合的初始化需要參考別的文章
 * 		1、獲取控制檯輸入  Scanner scan = new Scanner(System.in);
 * 		2、字串轉換為整數  Integer.parseInt(“sfad”); 此時需要用try catch 包裹。否則可能出錯。
 * 		3、控制檯程式必須加入主函式  主函式必須帶可憎的輸入引數
 * @author steven
 *
 */
public class Day1 {
	/**
	 * 程式功能提示語
	 */
	private static final String START_MSG = "輸入0-100之間的數字,判斷級別。輸入exit退出程式。";
	/**
	 * 退出提示語
	 */
	private static final String EXIT_MSG = "程式退出。";
	private static final String A_LEVEL = "A級";
	private static final String B_LEVEL = "B級";
	private static final String C_LEVEL = "C級";
	private static final String D_LEVEL = "D級";
	private static final String E_LEVEL = "E級";

	public static void main(String[] args) {
		convertInputToLevle();
	}
	/**
	 * 處理輸入,將輸入的數字分級
	 */
	public static void convertInputToLevle(){
		Integer inputGrade = 0;
		String readContent = "";

		Scanner scan = new Scanner(System.in);
		showMsg(START_MSG);
		while (true) {
			readContent = scan.nextLine();
			if (readContent.equalsIgnoreCase("exit")) {
				showMsg(EXIT_MSG);
				scan.close();
				break;
			}
			try {
				inputGrade = Integer.parseInt(readContent);
			} catch (Exception e) {
				System.out.println(e.getMessage());
				showMsg(START_MSG);
				continue;

			}
			if (inputGrade >= 0 && inputGrade <= 100) {
				//switchTest(inputGrade);
				ifTest(inputGrade);
			} else {
				showMsg(START_MSG);
			}
		}
	}

	/**
	 * 使用switch分級
	 * @param grade
	 */
	public static void switchTest(Integer grade) {
		Integer convertGrade = grade / 10;
		switch (convertGrade) {
		case 10:
			showMsg(grade + " 屬於 " + A_LEVEL);
			break;
		case 9:
			showMsg(grade + " 屬於 " + A_LEVEL);
			break;
		case 8:
			showMsg(grade + " 屬於 " + B_LEVEL);
			break;
		case 7:
			showMsg(grade + " 屬於 " + C_LEVEL);
			break;
		case 6:
			showMsg(grade + " 屬於 " + D_LEVEL);
			break;
		default:
			showMsg(grade + " 屬於 " + E_LEVEL);
			break;

		}
	}
/**
 * 使用if else 語句分級
 * @param grade
 */
	public static void ifTest(Integer grade) {
		if (grade >= 90 && grade <= 100) {
			showMsg(grade + " 屬於 " + A_LEVEL);
			return;
		}
		if (grade >= 80 && grade < 90) {
			showMsg(grade + " 屬於 " + B_LEVEL);
			return;
		}
		if (grade >= 70 && grade < 80) {
			showMsg(grade + " 屬於 " + C_LEVEL);
			return;
		}
		if (grade >= 60 && grade < 70) {
			showMsg(grade + " 屬於 " + D_LEVEL);
			return;
		}
		if (grade >= 0 && grade < 60) {
			showMsg(grade + " 屬於 " + E_LEVEL);
			return;
		}
	}
/**
 * 輸出提示公共函式
 * @param msg
 */
	public static void showMsg(String msg) {
		System.out.println(msg);
	}
}

相關文章