Java IO練習
使用輸入流讀取試題文件,每次顯示試題文件中的一道題目。讀取到字元「*」時暫停讀取,等待用戶從鍵盤輸入答案。用戶做完全部題目後。程式給出用戶的得分。
1) 試題內容如下:
(1)北京奧運是什麼時間開幕的?
A.2008-08-08 B. 2008-08-01
C.2008-10-01 D. 2008-07-08
********************
(2)下列哪個國家不屬於亞洲?
A.沙特 B.印度 C.巴西 D.越南
********************
(3)下列哪個國家最愛足球?
A.剛果 B.越南 C.寮國 D.巴西
********************
(4)下列哪種動物屬於貓科動物?
A.鬣狗 B.犀牛 C.大象 D.獅子
********************
程式運行如下:
(1)北京奧運是什麼時間開幕的?
A.2008-08-08 B. 2008-08-01
C.2008-10-01 D. 2008-07-08
輸入選擇的答案(A、B、C、D):A
(2)下列哪個國家不屬於亞洲?
A.沙特 B.印度 C.巴西 D.越南
輸入選擇的答案(A、B、C、D):
public static void main(String[] args) {
BufferedReader br = null;
Scanner scan = null;
try {
// 1. 造流
br = new BufferedReader(new FileReader("question.txt"));
scan = new Scanner(System.in);
// 2. 讀寫數據
String answer = "ACDD";
String data;
StringBuilder result = new StringBuilder();
int score = 0;
while ((data = br.readLine()) != null){
if (! data.startsWith("*")){
System.out.println(data);
}else{
System.out.print("Please input your answer: ");
result.append(scan.next().charAt(0));
}
}
for (int i = 0; i < result.length(); i++) {
if(answer.toLowerCase().charAt(i) == result.toString().toLowerCase().charAt(i)){
score += 25;
}
}
System.out.println("Final score is: " + score);
} catch (IOException e) {
e.printStackTrace();
} finally {
// 3. 關閉流資源
try {
if(br == null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
scan.close();
}
}