# 語言基礎練習-參考答案 ###### tags: `java` `exam` ## 目錄 - [基礎](#基礎) - [流程控制](#流程控制) - [資料結構](#資料結構) - [類別與物件](#類別與物件) - [大型程式](#大型程式) ## 基礎 1. Java標準輸出和標準輸入的物件為何? **參考答案** 標準輸出:System.out 標準輸入:System.in 2. 下面何者非邏輯運算子? a. && b. & c. || **參考答案** & > **說明** > > &為位元運算子 3. Java唯一的三元運算子為何? **參考答案** ?: 4. int和long型態有何不同? **參考答案** 資料長度不同,int長度為32位元,長度long為64位元。 int可以存放的數字範圍為:-2,147,483,648 to 2,147,483,647 long可以存放的數字範圍為:-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 5. 下面程式碼有何錯誤?該如何修正? ``` float a = 33.1; ``` **參考答案** 程式碼內預設小數數字為double,所以改成是馬會編譯錯誤,可以在小數後面加上「F」即可。 如:`float a = 33.1F;` 6. System.out物件裡的print()、println()和printf()三個方法有何不同? **參考答案** print():輸出字串但不換行。 println():輸出字串並換行。 printf():格式化輸出字串。 7. 如何將字串轉為int型態?請寫出程式碼。 **參考答案** 使用Integer.parseInt()方法 ``` int demo = Integer.parseInt("99"); ``` 8. 如何將long型態轉為int型態?請寫出程式碼。 **參考答案** 使用強制轉型 ``` long no1 = 100; int no2 = (int)no1; ``` 9. 請問`5 & 3`和`5 && 3` 運算出來結果有何不同? **參考答案** 1. `5 & 3`結果為1 2. `5 && 3`無法運算,因為&&的運算元只能是布林(true or false)。 10. 下面陳述句中,哪一個是資料型態?哪一個是變數名稱?哪一個是初始值? ``` String STR = "string"; ``` **參考答案** String: 資料型態 STR: 變數名稱 "string": 初始值 11. 資料型態`int`和`Integer`有何差異? **參考答案** int:基本資料型態 Integer:類別 12. 請問下面程式片段會輸出什麼到標準輸出? ``` System.out.println("3 + 4 = " + 3 + 4); ``` **參考答案** ``` 3 + 4 = 34 ``` > 後面的3 + 4會被當成字串來串接,而不會被當成數字來相加,如果想當成數字相加,可在兩邊加上小括號,如:`System.out.println("3 + 4 = " + (3 + 4));` ## 流程控制 1. 使用while迴圈,寫出加總2~99之間的偶數並顯示到標準輸出。 **參考答案** ``` public class App { public static void main(String[] args) { int sum = 0; for(int i = 2 ; i <= 99 ; i++) { if(i % 2 == 0) { sum += i; } } System.out.println("2 ~ 99之間的偶數總和為: " + sum); } } ``` 2. 請問下面程式碼片段會輸出什麼到標準輸出? ``` final int i = 10; if(i != 10); { System.out.println("Hello"); } else { System.out.println("Java"); } ``` **參考答案** 編譯錯誤:`Syntax error on token "else", delete this token`,if的判斷式後面不可以有分號。 3. break和continue差別是什麼? **參考答案** break:跳離迴圈 continue:忽略迴圈內接下來的程式碼,重新開始下一次的迴圈。 4. 請問下面程式碼片段會輸出什麼到標準輸出? ``` for(int i = 10 ; i <= 10 ; i++) i += 2; System.out.println(i); ``` **參考答案** 編譯錯誤,因為for迴圈超過一行程式碼必須加上區塊符號「{}」,否則第二行以後的陳述句都不屬於迴圈;此例因為System.out裡面會用到i變數,i變數屬於for迴圈內,所以外面不認識i變數,造成編譯錯誤。 5. 下面迴圈內的System.out會被執行幾次? ``` for(int i = 0 ; i < 100 ; i++) for(int j = 0 ; j < 100 ; j++) System.out.println("我會被執行幾次?"); ``` **參考答案** 10000次 > 外圈100 x 內圈100 = 10000次 6. while和do...while迴圈的差別是什麼? **參考答案** do...while迴圈至少會執行一次 7. 下面程式碼會輸出什麼到標準輸出? ``` String a = 10; switch(a) { case 10: System.out.println("10") case 8: System.out.println("8") case 6: System.out.println("6") case 0: System.out.println("0") default: System.out.println("default") } ``` **參考答案** 編譯錯誤,10是整數型態,無法被指派給a變數。 8. 下面程式碼會輸出什麼到標準輸出? ``` String a = new String("Hello"); String b = new String("Hello"); if(a == b) { System.out.println("相同"); } else { System.out.println("不相同"); } ``` **參考答案** 不相同 > 字串的內容比較需要透過equals()方法,否則只是比較兩個字串的參考,而非內容。 9. 使用for迴圈,在標準輸出顯示如下圖形: ``` * *** ***** ******* ``` **參考答案** ``` public class App { public static void main(String[] args) { for(int i = 1 ; i <= 4 ; i++) { for(int j = 0; j < i * 2 - 1 ; j++) System.out.print("*"); System.out.println(""); } } } ``` 10. 使用switch,讓使用者輸入一個英文字母,然後片段是母音還是子音,例如: ``` 請輸入一英文字母:a a是母音字母 請輸入一英文字母:t t是子音字母 ``` **參考答案** ``` import java.io.*; public class App { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("請輸入一個英文字母: "); String ch = br.readLine(); if(ch.length() != 1) { System.out.println("輸入錯誤!"); return; } switch(ch) { case "a": case "e": case "i": case "o": case "u": System.out.println(ch + "是母音"); break; default: System.out.println(ch + "是子音"); break; } } } ``` 11. 寫一程式,根據輸入的學生成績來判斷等級,規則如下: - 分數大於90並且小於等於100為:超優秀 - 分數大於80並且小於等於90為:優秀 - 分數大於70並且小於等於80為:良好 - 分數大於等於60並且小於等於70為:及格 - 分數小於60為:不及格 **參考答案** ``` import java.io.*; public class App { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("請輸入學生成績: "); int score = Integer.parseInt(br.readLine()); // - 分數大於90並且小於等於100為:超優秀 // - 分數大於80並且小於等於90為:優秀 // - 分數大於70並且小於等於80為:良好 // - 分數大於等於60並且小於等於70為:及格 // - 分數小於60為:不及格 if(score > 90 && score <= 100) System.out.println("超優秀"); else if(score > 80 && score <= 90) System.out.println("優秀"); else if(score > 70 && score <= 80) System.out.println("良好"); else if(score >= 60 && score <= 70) System.out.println("及格"); else if(score < 60 && score > 0) System.out.println("不及格"); else System.out.println("輸入錯誤!"); } } ``` ## 資料結構 1. 寫一程式,從1~10之間取5個不重複亂數,並顯示到標準輸出,例如: ``` 3 8 9 1 5 ``` **參考答案** ``` import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; public class App { public static void main(String[] args) { Set<Integer> set = new HashSet<>(); while(set.size() < 5) { int no = (int)(Math.random() * 10) + 1; set.add(no); } System.out.println(set.toString()); } } ``` 2. 寫一程式,不管使用者輸入什麼英文,一率轉為大寫後再輸出,例如: ``` 請輸入英文:Today is not my day. 輸出:TODAY IS NOT MY DAY. ``` **參考答案** ``` import java.io.BufferedReader; import java.io.InputStreamReader; public class App { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("請輸入英文:"); System.out.println("輸出:" + br.readLine().toUpperCase()); } } ``` 3. 寫一程式,將下列陣列反過來輸出: ``` int[] data = {55, 66, 77, 88, 99}; ``` 輸出為: ``` 99 88 77 66 55 ``` **參考答案** ``` import java.util.Arrays; import java.util.Collections; import java.util.List; public class App { public static void main(String[] args) { int[] data = {55, 66, 77, 88, 99}; System.out.println("處理前: " + Arrays.toString(data)); for(int i = 0; i < data.length / 2; i++) { int temp = data[i]; data[i] = data[data.length - i - 1]; data[data.length - i - 1] = temp; } System.out.println("處理後: " + Arrays.toString(data)); } } ``` 4. 寫一程式,讓使用者輸入任意個數字,然後顯示最小值、最大值和平均值。 **參考答案** ``` import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class App { public static void main(String[] args) throws Exception { List<Integer> nums = new ArrayList<>(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while(true) { System.out.print("請輸入數字(-1離開): "); int input = Integer.parseInt(br.readLine()); // 離開 if(input == -1) break; // 存入ArrayList nums.add(input); } int max = 0; // 用來存最大值 int min = nums.get(0); // 用來存最小值 int sum = 0; // 用來存總和 for(int i : nums) { if(i > max) max = i; else if(i < min) min = i; sum += i; } System.out.println("全部數字: " + nums); System.out.println("最小值: " + min + ", 最大值: " + max + ", 平均: " + sum / nums.size()); } } ``` 5. 請描述List、Set、Map容器個有什麼特色? **參考答案** List:陣列加強版,長度可以動態增加減少。 Set:元素不能重複。 Map:每一筆資料都是key-value的組合。 6. 請將下面陣列的所有元素加總後顯示出來: ``` int[] data = {34, 56, 78, 90, 12}; ``` **參考答案** ``` public class App { public static void main(String[] args) { int[] data = {34, 56, 78, 90, 12}; int sum = 0; for(int i : data) { sum += i; } System.out.println("總和為:" + sum); } } ``` 7. 請問下面程式碼會輸出什麼結果? ``` int a = 6; String[] strs = new String[6]; Arrays.fill(strs, "x"); System.out.println(Arrays.toString(strs)); ``` **參考答案** ``` [x, x, x, x, x, x] ``` 8. 將下面陣列的數字顯示到標準輸出,先顯示奇數,然後換行顯示偶數。 ``` int[] data = {34, 56, 78, 91, 13, 26, 69, 40}; ``` 輸出為: ``` 91 13 69 34 56 78 26 40 ``` **參考答案** ``` import java.util.ArrayList; import java.util.List; public class App { public static void main(String[] args) { int[] data = {34, 56, 78, 91, 13, 26, 69, 40}; List<Integer> odd = new ArrayList<>(); List<Integer> even = new ArrayList<>(); for(int i : data) { if(i % 2 == 0) even.add(i); else odd.add(i); } for(int o : odd) System.out.print(o + " "); System.out.println(""); for(int e : even) System.out.print(e + " "); System.out.println(""); } } ``` 9. 請問要取出陣列內所有元素有哪些方式? **參考答案** for迴圈、for-each迴圈 10. 陣列和List容器有哪些差異? **參考答案** a. 陣列為固定大小,可透過length資料成員取得;list為動態大小,可透過size()方法成員取得。 b. 陣列可以存放基本資料型態,List只能存放物件。 c. 陣列透過索引運算子存取元素,List透過get()方法存取元素。 d. List可以插入元素,陣列不行。 e. 陣列使用「=」賦值,List使用add()方法賦值。 11. 寫一程式,計算下面文章內的每個英文單字總共出現幾次: ``` Mary is a good person and she always like to go to school. She is a good student too. One day she got accident during walk to school. ``` 將輸出: ``` Mary: 1次 is: 2次 a: 2次 she: 3次 ... 以下省略 ``` > 每個單字的順序不需一樣 **參考答案** ``` import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class App { public static void main(String[] args) { String content = "Mary is a good person and she always like to " + "go to school. She is a good student too. One " + "day she got accident during walk to school."; // 去掉句點 content = content.replace(".", ""); // 用空白字元將每個單字做切割並存成一個字串陣列 String[] words = content.split(" "); // 將陣列轉成Set Set<String> targetSet = new HashSet<String>(Arrays.asList(words)); // 將Set轉成Map並做為Key Map<String, Integer> map = new HashMap<>(); // 計算次數並存入Map for(String str : targetSet) { map.put(str, wordCounts(content, str)); } // 顯示結果 for(String key : map.keySet()) { System.out.println(key + ": " + map.get(key) + "次"); } } // 計算單字在字串出現的次數方法 public static int wordCounts(String str, String findStr) { int lastIndex = 0; int count = 0; while(lastIndex != -1){ lastIndex = str.indexOf(findStr,lastIndex); if(lastIndex != -1){ count ++; lastIndex += findStr.length(); } } return count; } } ``` 12. 下面有一陣列,請將該陣列內的資料打亂後輸出,每次執行都會以不同的順序。 ``` String[] names = {"Aaron", "Apple", "Adam", "Abner", "Andy", "Ada", "Astrid", "Alan"}; ``` **參考答案ㄧ** 使用ArrayList+while迴圈 ``` import java.util.ArrayList; public class App { public static int random(int start, int end) { return (int)(Math.random() * (end - start + 1)) + start; } public static void main(String[] args) { String[] name = {"Aaron", "Apple", "Adam", "Abner", "Andy", "Ada", "Astrid", "Alan"}; ArrayList<Integer> indexs = new ArrayList<>(); // 取出8個隨機索引, 且不能重複 while(indexs.size() < 8) { int index = random(0, 7); // 判斷該隨機數是否已經存在ArrayList中 if(indexs.indexOf(index) == -1) indexs.add(index); } // 透過隨機取出的索引印出結果 for(int j = 0 ; j < indexs.size() ; j++) { System.out.println("第" + (j + 1) + "位: " + name[indexs.get(j)]); } } } ``` **參考答案二** 使用Java內建方法`java.util.Collection.shuffle()` ``` import java.util.Arrays; import java.util.Collections; import java.util.List; public class App { public static void main(String[] args) { String[] name = {"Aaron", "Apple", "Adam", "Abner", "Andy", "Ada", "Astrid", "Alan"}; // 將陣列轉成List List<String> names = Arrays.asList(name); // 使用Collection.shuffle方法 Collections.shuffle(names); // 透過隨機取出的索引印出結果 for(int j = 0 ; j < names.size() ; j++) { System.out.println("第" + (j + 1) + "位: " + names.get(j)); } } } ```