我试图确定在阵列中使用0-999之间的每个数字的次数。 另外,我想要格式化元素,使其始终为3位数字。而不是' 21'它将是' 021',' 5'将是' 005' Netbeans说使用增强型循环代替for(int x = 0; x
public static void main(String[] args) {
//Creator of random number 0-999
Random creator = new Random(999);
int lotto[][] = new int[1000][2];
int count = 0;
for(int x=0;x<lotto.length; x++){
for(int y = 0; y < lotto[x].length; y++){
//Fills element with random number
lotto[x][y] = creator.nextInt(999);
}
}
//Place holder to print out array
for(int[] a: lotto){
System.out.println(Arrays.toString(a));
}
}
}
编辑: 我试过这个
for(int x=0;x<lotto.length; x++){
for(int y = 0; y < lotto[x].length; y++){
//Fills element with random number
++lotto[creator.nextInt(999)][creator.nextInt(999)];
}
}
for(int j=0; j < lotto.length;j++){
System.out.println(j +""+ lotto[j]);
}
但现在程序没有运行。我认为++ lotto计算元素的使用时间是正确的。
编辑2:
List<Integer> list = new ArrayList<>();
for(int x=0;x<lotto.length;x++){
for(int y=0; y<lotto[x].length; y++){
list.add(lotto[x][y]);
}
}
for(int x=0; x<1000; x++){
if(list.contains(x)){
int index = 0;
int countList = 0;
while(index!= -1){
countList++;
list.remove(index);
index = list.indexOf(x);
}
System.out.println(x +" Hit "+ countList + "time(s)");
}
}
当数组打印出来时,列表打印输出的数量少于数组中找到的元素数量。
更新: 由于某种原因,现在下面的源计算列表,该数字与用户输入的次数不匹配。即:用户输入200,它的计数200被使用了两次但是列表只打印出它被发现一次
for(int x=0;x<lotto.length;x++){
for(int y = 0; y < lotto[x].length; y++){
if(lotto[x][y]== lottery)
count++;
}
}
答案 0 :(得分:0)
您可以在一维列表中加载2D数组,以计算0到999之间每个数字的出现次数。因此,您可以从ArrayList的方法中受益。 计数代码:
int occurences[] = new int[1000];
int max = 0;
for(int x=0; x<1000; x++){
if (liste.contains(x)) {
int index = liste.indexOf(x);
int count = 0;
while(index != -1){
count++;
liste.remove(index);
index = liste.indexOf(x);
}
occurences[x] = count;
if (count >= max) max = count;
}
else occurences[x] = 0;
}
for (int i = 0; i < occurences.length; i++){
if (occurences[i] == max)
System.out.println("valeur " + i + " --> " + max);
}
答案 1 :(得分:0)
好的,如果我正确理解这一点,你需要一个包含1000行和2列的2D数组。您为每列分配一个随机数,因此2000个值都在0-999范围内。您似乎已经正确地执行了该部分,但您仍然需要计算每个数字(0-999)的出现次数?
如果是这样,你应该创建第二个数组,即int tmp = creator.nextInt(999)
,然后在for循环中将随机int放入2D数组中,你可能希望将其更改为countOccurences[tmp]+=1
并将其分配给2D阵列的方式与 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>name you want to see</display-name>
<welcome-file-list>
<welcome-file>view/yourFile.jsp</welcome-file>
</welcome-file-list>
</web-app>
相同。然后例如,如果int 47出现2次,则countOccurences [47]将等于2.