close
標題:

JAVA HELP

發問:

 

此文章來自奇摩知識+如有不便請留言告知

有無人知點樣可以叫個JAVA係個test file 到randomly chose 一行.. print 個行ga 第二個出黎做問題 個user 會答個答案 如果個答案個個行ga 第一個一樣ga 話就printd字出黎? 更新: 仲有ar... 我想用array 要吾要個test file 有幾多行ga? 有222行 ... 希望有高手幫幫忙~!

最佳解答:

我不太明白你「個行第一個」和「個行第二個」是甚應. 我例設你的 text file 是下面的格式: Answer 001;;;Question 001 Answer 002;;;Question 002 Answer 003;;;Question 003 . . . Answer 222;;;Question 222 即是每一行有兩個資料,第一個是答案,第二個是間題,答案和問題之間有 ;;; 符號隔著(如果你的相隔符號不是 ;;; 請自行轉到其他符號) 我又假設你會 random print 一個問題出來,user 答了之後,如果答案與那問題的答案一樣,就會 print 「you are correct!」出來。相反就會 print 「sorry! you are wrong!「(你可以隨意更改這些 printout 內容,這只是假設) 下面的 code 就做了你想做的邏輯: import java.io.*; int qnum = 222; String[] questions = new String[qnum]; String[] answers = new String[qnum]; try { //1. to read the file and put to the array BufferedReader fileIn = new BufferedReader(new FileReader(”filename”)); String line = null; int counter = 0; while((line = fileIn.readLine()) != null) { String[] tokens = line.split(”;;;”); questions[counter] = tokens[0]; questions[counter] = tokens[1]; counter = counter+1; } fileIn.close(); //after this //the questions array will store the 222 questions //the answers array will store the 222 answers //2. to random select the question int randomNum = (int)Math.floor(Math.random()*qnum); //3. to print out the question System.out.println(questions[randomNum]); //4. to read the answer from the user BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); line = in.readLine(); //5. to check the user input with the answer of the questions and print the result if(line.equals(answers[randomNum])) { System.out.println(”You are correct!”); } else { System.out.println(”Sorry! You are wrong!”); } } catch(FileNotFoundException fnfe) { System.out.println(”File not found”); } catch(IOException ioe) { System.out.println(”I/O Error”); } 小小補充: - 上面的 code 面裡 filename 是你裝著問題和答案的 filename,請自行轉到你 file 的正確路徑。 - 上面的 code,如果你要 loop 住給 user 去答一堆 questions,可以自由用 while loop 去把 2 至 5 的步驟運行多次。 - 上面的 code 為避免出現亂碼,double quote (”) 符號使用了全型顥示。如果你要 copy 出來使用,請自己轉用半型符號。 - 上面的 code 為了對齊使用了全型空格。如果你要 copy 出來使用,請自己轉用半型空格或者 tab。 - 上面的 code 假設了有 222 個問題和答案,如果你要 dynamic load,可以再找我,因為會 involve 到另一些 code。

其他解答:E2A5F59BAA12C031
arrow
arrow

    lgzrelv 發表在 痞客邦 留言(0) 人氣()