gpt4 book ai didi

java - 在 Java 中使用数组

转载 作者:行者123 更新时间:2023-11-29 03:41:38 26 4
gpt4 key购买 nike

所以我在 java 中使用数组,我遇到了一个问题,我试图列出长度为 100 的数组中出现次数最少的位置,范围为0-9。我正在使用第二个数组来计算出现的次数,直到我的最后一段代码之前一切正常。

import java.util.Random;

public class Program6
{
public static void main(String[] args)
{
int[] bigArray = new int[100];
int[] count = new int[10];


for (int i = 0; i < bigArray.length ;i++ )
{
bigArray[i] = (int)(Math.random() * 10);
}
for (int i = 0; i < bigArray.length ;i++ )
{
System.out.println(bigArray[i] + " ");
}
for(int i = 0; i < bigArray.length; i++)
{
count[bigArray[i]]++;
}



for (int i = 0, j = 0; i < count.length ;i++, j++)
System.out.println("count for " + j +" is: " + count[i] + " ");

int min = count[0];
int indexOfMin = 0;

for ( int i =1; i < count.length; i++)
{ if (count[i] < min )
{
min = count[i];
indexOfMin = i;
}
}

System.out.println("\nThe number " + indexOfMin + " only appears " + min + " times in the array.");
System.out.println("It appears in the large array at: ");

\\this guy right here
for ( int i = 0 ; i < bigArray.length; i++)
{ if (bigArray[i] == min )
{
System.out.println("bigArray["+ i + "]");

}
}

}

它应该只列出数组位置。但它返回的不仅仅是出现次数最少的整数的位置,即使限定符使用的是变量 min

什么给了?我错过了什么?

没有输入,返回的输出是

8 
..
4
count for 0 is: 18
count for 1 is: 6
count for 2 is: 9
count for 3 is: 9
count for 4 is: 16
count for 5 is: 4
count for 6 is: 12
count for 7 is: 8
count for 8 is: 7
count for 9 is: 11

The number 5 only appears 4 times in the array.
It appears in the large array at:
bigArray[3]
bigArray[6]
bigArray[10]
bigArray[23]
bigArray[25]
bigArray[39]
bigArray[44]
bigArray[48]
bigArray[49]
bigArray[50]
bigArray[51]
bigArray[57]
bigArray[58]
bigArray[67]
bigArray[84]
bigArray[99]

这是完美的,除了 bigArray[] 列表。当数组等于最少出现的数字时,它应该只显示索引所在的位置。

最佳答案

您正在比较数字的计数。请改用号码。更新

//this guy right here 
for ( int i = 0 ; i < bigArray.length; i++)
{ if (bigArray[i] == min )
{
System.out.println("bigArray["+ i + "]");

}
}

indexOfMin 用作

`//this guy right here 
for ( int i = 0 ; i < bigArray.length; i++)
{ if (bigArray[i] == indexOfMin)
{
System.out.println("bigArray["+ i + "]");

}
}

关于java - 在 Java 中使用数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12867519/

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