自九月底以来,我一直在学习软件开发硕士转换类(class),主要语言是 Java。 我们对实际情况进行了第一次评估,我希望得到一些指导。
我们必须创建一个数组来存储 100 个整数(所有整数都在 1 到 10 之间),这些整数是由随机数生成器生成的,然后每行打印出该数组的 10 个数字。对于第二部分,我们需要扫描这些整数,计算每个数字出现的频率并将结果存储在第二个数组中。
我已经完成了第一部分,但我对如何做第二部分感到困惑。我一直在查看扫描仪类,看看它是否有任何我可以使用的方法,但我没有看到任何方法。谁能给我指出正确的方向 - 不是答案,而是它来自哪个库?
到目前为止的代码:
import java.util.Random;
public class Practical4_Assessed
{
public static void main(String[] args)
{
Random numberGenerator = new Random ();
int[] arrayOfGenerator = new int[100];
for (int countOfGenerator = 0; countOfGenerator < 100; countOfGenerator++)
arrayOfGenerator[countOfGenerator] = numberGenerator.nextInt(10);
int countOfNumbersOnLine = 0;
for (int countOfOutput = 0; countOfOutput < 100; countOfOutput++)
{
if (countOfNumbersOnLine == 10)
{
System.out.println("");
countOfNumbersOnLine = 0;
countOfOutput--;
}
else
{
System.out.print(arrayOfGenerator[countOfOutput] + " ");
countOfNumbersOnLine++;
}
}
}
}
谢谢, 安德鲁
最佳答案
每次获得随机数时,将其存储在 int
变量中,然后递增“计数数组”的相应存储桶:
int[] countingArray = new int[10];
for (int countOfGenerator = 0; countOfGenerator < 100; countOfGenerator++) {
// Get a number between 0 and 9 (inclusive); we'll add 1 to it in a moment
int number = numberGenerator.nextInt(10);
// Update your counts (array indexes start at 0, which is why we
// haven't added to `number` yet)
countingArray[number]++;
// Store the actual number, which we add to because the assignment
// is for 1-10, not 0-9
arrayOfGenerator[countOfGenerator] = number + 1;
}
现在,countingArray[0]
是您有多少个 1
,countingArray[1]
是多少个 2<例如,其中
你有。x
是 1 到 10(包含 1 到 10),countingArray[x - 1]
是数字 x
的数量
关于java - 如何扫描数组以获取某些信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13099516/