gpt4 book ai didi

java - 我的嵌套 for 循环有问题吗?计算和递增数组的值

转载 作者:行者123 更新时间:2023-11-30 07:08:07 25 4
gpt4 key购买 nike

因此,我生成了 0 到 9 之间的 100 个数字。我将这 100 个数字存储在一个名为“数组”的数组中。然后我有一个名为“count”的数组。它有 10 个元素,我想检查以下内容:对于“array”中的每个元素,如果它等于 0-9,则 count[0-9] 递增 1,count[0] = 数字 0 出现的次数以及所以计数[1] = 1,计数[2] = 2 ...。我只是不断得到大约 20k 个数字的输出,我想?每个元素的总和?,不知道为什么。我想知道我的 for 循环是否存在重大问题?

import java.util.*;

class RandomInt {
public static void main(String[] args) {
int size = 100;
int max = 10;
int[] array = new int[size];
int[] count = new int[max]; //count[0,0,0,0,0,0,0,0,0,0]
int loop = 0;

Random generator = new Random();


for (int i = 0; i < size; i++) {
array[i] = generator.nextInt(max); // Generates 100 random numbers between 0 and 9 and stores them in array[]
System.out.print(array[i]);
for (int x = 0; x < size; x++) {// loop through 10 elements in count
for(int j = 0; j < 10; j++){ //loop through 100 elements in array
if (array[x] == j) {// loop through each 100 elements of array[x] and if element array[x] = value
count[j] += 1; // then count[x] = x + 1
System.out.print(count[j]);
}
}
}
}

System.out.println("0 appears " + count[0] + " times.");
}
}

最佳答案

您的登录是完美的,我发现您犯的唯一错误是括号......!

使用第一个循环生成数字,然后使用不同的 for 循环计算出现的次数。

这是您的代码的修改版本,它生成 10 个数字并计算单个数字的出现次数.....

public class RandomInt {
public static void main(String[] args) {
int size = 10;
int max = 10;
int[] array = new int[size];
int[] count = new int[max]; //count[0,0,0,0,0,0,0,0,0,0]
int loop = 0;

Random generator = new Random();


for (int i = 0; i < size; i++)
{
array[i] = generator.nextInt(max); // Generates 100 random numbers between 0 and 9 and stores them in array[]
System.out.print(array[i]+" ");
}

for (int x = 0; x < size; x++)
{// loop through 10 elements in count
for(int j = 0; j < 10; j++)
{ //loop through 100 elements in array
if (array[x] == j)
{// loop through each 100 elements of array[x] and if element array[x] = value
count[j] += 1; // then count[x] = x + 1
//System.out.print(count[j]);
}
}

}

System.out.println("3 appears " + count[3] + " times.");
}

关于java - 我的嵌套 for 循环有问题吗?计算和递增数组的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24248499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com