java程式設計

程式設計題目我有困難

懇請各位大大幫個忙 ~"~

題目如下:

3. 請自行建立一個名為Iteration.txt 檔,並在txt 檔中鍵入一個大於1000 且小於

3000 的整數,請寫一程式,讀取Iteration.txt 檔中的整數(假設為n),並隨

機產生n 個介於1~6(包含1 跟6)的正整數,並且計算每個數字的產生個數與

出現之機率,然後秀於螢幕上,除此之外,亦須將秀於螢幕上之結果,存成

於result.txt 檔案之中。此題上傳作業時,請一併繳交Iteration.txt 檔,否則將

扣10 分。

2 Answers

Rating
  • 8 years ago
    Favorite Answer

    public class Iteration {

    /**

    * @param Figure

    */

    public static void main(String[] args) {

    try {

    FileReader fr = new FileReader("D:\\eclipse\\workspace\\practice\\bin\\Iteration.txt");

    BufferedReader br = new BufferedReader(fr);

    int num = 0;

    num = Integer.parseInt(br.readLine());

    int[] list = new int[num];

    Random random = new Random();

    DecimalFormat df = new DecimalFormat("###,###,###");

    Double count1 = 0.0;

    Double count2 = 0.0;

    Double count3 = 0.0;

    Double count4 = 0.0;

    Double count5 = 0.0;

    Double count6 = 0.0;

    if (num > 1000 && num < 3000) {

    for (int i = 0; i < num; i++) {

    // random => 0-5

    list[i] = random.nextInt(6)+1;

    if (list[i] == 1) {count1++;}

    else if (list[i] == 2) {count2++;}

    else if (list[i] == 3) {count3++;}

    else if (list[i] == 4) {count4++;}

    else if (list[i] == 5) {count5++;}

    else if (list[i] == 6) {count6++;}

    }

    for (int j : list) {

    System.out.print(j + " ");

    }

    System.out.println("");

    System.out.println("");

    System.out.println("1 出現次數為:" + df.format(count1) + " 次, 機率為:" + df.format((count1/num)*100) + "%");

    System.out.println("2 出現次數為:" + df.format(count2) + " 次, 機率為:" + df.format((count2/num)*100) + "%");

    System.out.println("3 出現次數為:" + df.format(count3) + " 次, 機率為:" + df.format((count3/num)*100) + "%");

    System.out.println("4 出現次數為:" + df.format(count4) + " 次, 機率為:" + df.format((count4/num)*100) + "%");

    System.out.println("5 出現次數為:" + df.format(count5) + " 次, 機率為:" + df.format((count5/num)*100) + "%");

    System.out.println("6 出現次數為:" + df.format(count6) + " 次, 機率為:" + df.format((count6/num)*100) + "%");

    } else {

    System.out.println("Iteration.txt 數值有誤");

    }

    } catch (FileNotFoundException e) {

    e.printStackTrace();

    } catch (IOException e) {

    e.printStackTrace();

    }

    }

    }

    2013-01-22 16:02:54 補充:

    FileReader 的路徑請自行修正

  • John
    Lv 7
    8 years ago

    You have to copy the result to result.txt as it was generated by the program randomly.

    https://docs.google.com/document/d/10-Vs0GhRBDj9Yv...

    Source(s): myself
Still have questions? Get your answers by asking now.