这是我即将到来的大学实习的代码:
import java.util.Random;
public class Practical4_Assessed
{
public static void main(String[] args)
{
Random numberGenerator = new Random ();
int[] arrayOfGenerator = new int[100];
int[] countOfArray = new int[10];
int count;
for (int countOfGenerator = 0; countOfGenerator < 100; countOfGenerator++)
{
count = numberGenerator.nextInt(10);
countOfArray[count]++;
arrayOfGenerator[countOfGenerator] = count + 1;
}
int countOfNumbersOnLine = 0;
for (int countOfOutput = 0; countOfOutput < 100; countOfOutput++)
{
if (countOfNumbersOnLine == 10)
{
System.out.println("");
countOfNumbersOnLine = 0;
countOfOutput--;
}
else
{
if (arrayOfGenerator[countOfOutput] == 10)
{
System.out.print(arrayOfGenerator[countOfOutput] + " ");
countOfNumbersOnLine++;
}
else
{
System.out.print(arrayOfGenerator[countOfOutput] + " ");
countOfNumbersOnLine++;
}
}
}
System.out.println("");
System.out.println("");
String occurrencesReport = "";
String graph = "";
for (int countOfNumbers = 0; countOfNumbers < countOfArray.length; countOfNumbers++)
{
occurrencesReport += "The number " + (countOfNumbers + 1) +
" occurs " + countOfArray[countOfNumbers] + " times.";
if (countOfNumbers != 9)
graph += (countOfNumbers + 1) + " ";
else
graph += (countOfNumbers + 1) + " ";
for (int a = 0; a < countOfArray[countOfNumbers]; a++)
{
graph += "*";
}
occurrencesReport += "\n";
graph += "\n";
}
System.out.println(occurrencesReport);
System.out.println(graph);
int max = 0;
int test = 0;
for (int counter = 0; counter < countOfArray.length; counter++)
{
if (countOfArray[counter] >= max)
{
max = countOfArray[counter];
test = counter + 1;
}
}
System.out.println("The number that appears the most is " + test + ".");
}
}
该程序创建一个数组,该数组将存储 100 个整数(所有整数都在 1 到 10 之间),这些整数由随机数生成器生成,然后每行打印出该数组的 10 个数字。然后它扫描这些整数,计算每个数字出现的频率,并将结果存储在第二个数组中。在此之后,它会输出一个星号水平条形图,显示每个数字出现的频率,然后最终输出出现频率最高的数字。
我以为我已经完全完成了代码,但我刚刚意识到如果多个数字出现相同的次数,我的代码的最后一部分将无法处理这个问题,例如如果数字 3 和 5 都出现 12有时,代码只能产生其中之一。
有没有人有办法解决这个问题?
谢谢,安德鲁