我最近用Python创建了一个非常简单的练习程序,该程序需要用户输入并掷骰子。代码是:
import random
import sys
import math
def roll(rolls, sides, results):
for rolls in range(1, rolls + 1):
result = random.randrange(1, sides + 1)
print result
results.append(result)
def countf(rolls, sides, results):
i = 1
print "There were", rolls, "rolls."
for sides in range(1, sides + 1):
if results.count(i) != 1:
print "There were", results.count(i), i,"s."
else:
print "There was", results.count(i), i
i = i + 1
if i == sides:
break
rolls = input("How many rolls? ")
sides = input("How many sides of the die? ")
results = []
roll(rolls, sides, results)
countf(rolls, sides, results)
(实际上,这是一个较大程序的一部分,因此我不得不剪切掉一些粘贴内容,而我可能会漏掉一些东西)。
因此,我决定将其翻译为Java。请注意此处的算法:获取随机数,将其打印,将其附加到数组中,然后在末尾计算数组中每个数字的数量,然后打印出该值。问题是,我不知道如何在Java语法中执行
someArray.count(someIndex)
的等效功能。所以到目前为止,我的Java程序看起来像这样:import java.util.*;
public class Dice {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
final static int TIMES_TO_ROLL = getInt("Times to roll?");
Random flip = new Random();
int[] results = new int[TIMES_TO_ROLL];
for (int i = 0; i < TIMES_TO_ROLL; i++) {
int result = flip.nextInt(6);
System.out.println(result);
results[i] = result;
}
}
public static int getInt(String prompt) {
System.out.print(prompt + " ");
int integer = input.nextInt();
input.nextLine();
return integer;
}
}
那么有人可以帮助我处理数组计数代码吗?我知道这可能不是定义的方法,因为毕竟Python是更高级别的,所以我可以创建自己的数组计数方法,但是我想知道Java是否像Python一样有预定义的方法。
编辑:我管理这样的事情:
public static int arrayCount(int[] array, int item) {
int amt = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == item) {
amt++;
}
else {
amt = amt;
}
}
return amt;
}
编辑:出于兴趣,假设我使用命令提示符运行我的Java程序和Python.exe(Python的命令提示符控制台),哪一个会更快(换句话说,对于相同的代码,哪种语言会有更好的性能? )?
最佳答案
有几个库可以为您完成此操作:
Google Guava的MultiSet
Apache Common的Bag
但是对于如此简单的事情,您可能会认为额外的库有点多余。
您也可以使用int[]
自己执行此操作。假设您的骰子使用整数,则将数字滚动后引用数组中的索引,然后递增该索引处的值。当您需要检索给定数字的值时,请通过索引查找其值。
private static final int NUMBER_DICE_SIDES = 6;
public static void main(String[] args) {
final static int TIMES_TO_ROLL = getInt("Times to roll?");
Random flip = new Random(NUMBER_DICE_SIDES);
int[] results = new int[NUMBER_DICE_SIDES];
for (int i = 0; i < TIMES_TO_ROLL; i++) {
int result = flip.nextInt;
System.out.println(result);
results[result]++;
}
for(int i = 0; i < NUMBER_DICE_SIDES; ++i) {
System.out.println((i+1)+"'s: " + arraysCount(results, i));
}
}
public static int arrayCount(int[] array, int item) {
return array[item];
}
关于java - 计算元素在数组中出现的次数-Java,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11053607/