在过去的几个小时左右的时间里,我一直在尝试从 ArrayList
中找到模式。在程序中,您还可以找到最大值、最小值、中值和平均值。我已经弄清楚了所有这些,但我无法完成该模式。我不断收到 IndexOutOfBoundsException
。这是到目前为止我的代码:
public String getMode(){
int mode = 0;
int count = 0;
for ( int i : file1 ){
int x = file1.get(i);
int tempCount = 1;
for(int e : file1){
int x2 = file1.get(e);
if( x == x2)
tempCount++;
if( tempCount > count){
count = tempCount;
mode = x;
}
}
}
return ("The mode is " + mode);
}
我收到的错误是:
java.lang.IndexOutOfBoundsException: Index: 181, Size: 108
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at FunNumber2.getMode(FunNumber2.java:75)
at FunNumber2Tester.main(FunNumber2Tester.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
最佳答案
这是你的问题
for ( int i : file1 ){
修改为
for ( int i = 0; i< file1.size() ; i++ ){
这个语法
for ( int i : file1 ){
为您提供 file1 的迭代值,这意味着如果 file1 = List([4,5,6])
那么在循环的第一次迭代中 i == 4 不是0
.
显然这也适用于第二个循环。
或者你可以改变
for ( int i : file1 ){
int x = file1.get(i);
至
for ( int i : file1 ){
int x = i;
它会解决你的问题。 希望有帮助。
关于java - 查找 ArrayList Java 的众数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20808673/