【发布时间】:2021-02-16 17:13:52
【问题描述】:
所以我试图从一个文件中读取,其中包含超过 10000000 个数字,范围为 1-6。本质上,这个练习的重点是模拟掷骰子,我需要找到每个数字被掷出的概率。我编写了将随机数 1-6 写入文件的代码:
public static void main(String[]args)throws IOException{
Scanner kb = new Scanner(System.in);
PrintWriter pw = new PrintWriter(new File("Rolls.txt"));
System.out.println("Input a number for the amount of rolls");
long rolls = kb.nextLong();
for(int i = 0; i< rolls; i++){
if(i % 20 == 0){
pw.println();
}
else{
pw.print(((int)(Math.random()*6)+1) + ",");
}
}
pw.close();
}
所以使用这个文件,我想我应该将整行作为字符串读取,然后以逗号分隔该行,然后将字符串更改为 longs/ints。我正在努力解决的是我应该计算 1 .... 6 的数量并将该数字存储到另一个数组中,然后获取该数组的每个元素并找到它被滚动的概率。到目前为止,我为第二部分提供的代码如下。我尝试了一些东西,但没有任何效果,我被难住了。
public static void main(String[]args) throws IOException{
Scanner in = new Scanner(new File("Rolls.txt"));
long[] list = {0,0,0,0,0,0};
while ( in.hasNextLine()){
String line = in.nextLine();
String[] numbers = line.split(",");
}
感谢任何帮助。谢谢!
【问题讨论】:
-
您需要遍历
numbers中的项目,将每个项目从字符串转换为整数(参见Integer.parseInt),然后在line中的相应索引处递增项目(即line[roll]++). -
您遇到了什么具体问题?您尝试了哪些方法,但没有成功?
-
“我尝试了一些东西,但没有工作”不是一个有效的问题描述。
标签: java simulation dice