# java程式設計

3. 請自行建立一個名為Iteration.txt 檔，並在txt 檔中鍵入一個大於1000 且小於

3000 的整數，請寫一程式，讀取Iteration.txt 檔中的整數（假設為n），並隨

Rating
• 8 years ago

public class Iteration {

/**

* @param Figure

*/

public static void main(String[] args) {

try {

int num = 0;

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 補充：