gpt4 book ai didi

java - 如何在List/ArrayList中查找出现的位置

转载 作者:行者123 更新时间:2023-12-01 07:28:29 25 4
gpt4 key购买 nike

我有一个关于如何查找列表中出现次数的问题。就我而言,对于我的程序的一部分,我试图查找飓风类别中 1、2、3 和 4 的出现次数并显示它们。我尝试使用 for 循环和 if 语句,但是当我运行它时,输出为零。我怎样才能解决这个问题?任何帮助将不胜感激。下面是我的程序的片段:

飓风2.java:

// category 1 occurrence
int i = 0;
int ii = 0;
int category1 = category.get(i);
for(int j = 0; j < category.size(); j++){
if(category1 == 1){
ii++;
}
}
System.out.printf("%1s%10d%n", "Category 1 occurrence ~", ii);

运行时我得到这个:

run:
Hurricanes 1980 - 2006

Year Hurricane Category Pressure(mb) Wind Speed (mph)
____________________________________________________________________________________
1980 Allen 2 100 945
1983 Alicia 2 100 962
1984 Diana 2 100 949
1985 Bob 1 65 1002
1985 Danny 1 80 987
1985 Elena 2 100 959
1985 Gloria 1 90 942
1985 Juan 1 75 971
1985 Kate 1 85 967
1986 Bonnie 1 75 990
1986 Charley 1 65 990
1987 Floyd 1 65 993
1988 Florence 1 70 984
1989 Chantal 1 70 986
1989 Hugo 3 120 934
1989 Jerry 1 75 983
1991 Bob 1 90 962
1992 Andrew 4 145 922
1993 Emily 2 100 960
1995 Erin 1 85 973
1995 Opal 2 100 942
1996 Bertha 1 90 974
1996 Fran 2 100 954
1997 Danny 1 70 984
1998 Bonnie 1 95 964
1998 Earl 1 70 987
1998 Georges 1 90 964
1999 Bret 2 100 951
1999 Floyd 1 90 956
1999 Irene 1 70 987
2002 Lili 1 80 963
2003 Claudette 1 80 979
2003 Isabel 1 90 957
2004 Alex 1 70 972
2004 Charley 4 130 941
2004 Gaston 1 65 985
2004 Frances 1 90 960
2004 Ivan 2 105 946
2004 Jeanne 2 105 950
2005 Cindy 1 65 992
2005 Dennis 4 130 930
2005 Emily 4 135 929
2005 Irene 1 85 975
2005 Katrina 4 150 902
2005 Maria 2 100 960
2005 Nate 1 80 979
2005 Ophelia 1 80 976
2005 Phillipe 1 70 985
2005 Rita 4 150 897
2005 Stan 1 70 979
2005 Vince 1 65 987
2005 Wilma 4 150 882
2005 Beta 2 100 960
2005 Epsilon 1 75 979
2006 Ernesto 1 65 995
2006 Florence 1 80 972
2006 Gordon 2 105 955
2006 Helene 2 110 954
2006 Isaac 1 75 985
____________________________________________________________________________________
Average ~ 1 91 963
Maximum ~ 4 150 1002
Minimum ~ 1 65 882
Category 1 occurrence ~ 0
BUILD SUCCESSFUL (total time: 0 seconds)

最佳答案

使用 int[] 作为计数器,如下所示:

// we won't use the 0 position
int[] counter = new int[5];

迭代所有类别。每次找到新类别时,请向计数器添加一个:

for (int i = 0; i < category.size(); i++) {
int cat = category.get(i);
// assuming that cat is 1, 2, 3 or 4
counter[cat]++;
}

当迭代结束时,counter[1]将保存第一个类别的出现次数,counter[2]将保存第二个类别的出现次数类别等。

关于java - 如何在List/ArrayList中查找出现的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20644586/

25 4 0