進位轉換:
【16進位】 轉成 【2進位】,並且印出算式
程式碼
【16進位】 轉成 【2進位】,並且印出算式
截圖
程式碼
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class _16_to_2 { // 顯示全型數字 public static String quan_xing(String s) { s = s.replace("0", "0");//如果字串內有半型的0,則變成全型的0 s = s.replace("1", "1"); s = s.replace("2", "2"); s = s.replace("3", "3"); s = s.replace("4", "4"); s = s.replace("5", "5"); s = s.replace("6", "6"); s = s.replace("7", "7"); s = s.replace("8", "8"); s = s.replace("9", "9"); s = s.replace("A", "A"); s = s.replace("B", "B"); s = s.replace("C", "C"); s = s.replace("D", "D"); s = s.replace("E", "E"); s = s.replace("F", "F"); return s; } public static void main(String[] args) throws IOException { BufferedReader sc = new BufferedReader( new InputStreamReader(System.in));//從鍵盤讀取文字 System.out.println("16進位→2進位\n//-----------------------"); System.out.print("輸入進位值:"); boolean cuo = false;// 判斷是否有錯誤 String cuo_zi = "";//判斷錯誤的文字 String shu_ru =sc.readLine().toUpperCase();// 輸入的值 int chang = shu_ru.length();// 字串長度 String in = "";// 儲存【最後印出結果】 String[] xian = new String[chang];// 計算用 String sum = "";// 顯示【答案】 String[] s16 = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F" }; String[] s2 = { "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111" }; in += ("16進位:" + shu_ru + " → 2進位" + "\n\n"); for (int i = 0; i < chang; i++) {// 印出個別16進位的符號(定位) xian[i] = shu_ru.substring(i, i + 1); in += " ┌─" + quan_xing(xian[i]) + "┐"; } in += "\n";// 換行 for (int i = 0; i < chang; i++) { for (int j = 0; j < s2.length; j++) { if (xian[i].equals(s16[j])) {// 印出計算結果 in += " " + quan_xing(s2[j]); sum += s2[j];// 儲存答案 } } // 判斷是否有錯字 if (!(xian[i].equals("0") || xian[i].equals("1") || xian[i].equals("2") || xian[i].equals("3") || xian[i].equals("4") || xian[i].equals("5") || xian[i].equals("6") || xian[i].equals("7") || xian[i].equals("8") || xian[i].equals("9") || xian[i].equals("A") || xian[i].equals("B") || xian[i].equals("C") || xian[i].equals("D") || xian[i].equals("E") || xian[i].equals("F"))) { cuo = true; cuo_zi += xian[i];// 錯字 } } in += "\n\n答案: " + sum; if (cuo == true) {// 如果有錯字 in=("檢視結果:\n有異音的字: 【" + cuo_zi + "】"); } System.out.println(in);// 顯示計算結果 System.gc();// 釋放記憶體 } } |