gpt4 book ai didi

java - 对数组进行排序并计算其元素

转载 作者:行者123 更新时间:2023-11-29 06:38:42 25 4
gpt4 key购买 nike

我尝试对数组进行排序并计算数组元素请帮我找到缺少的东西,调试了很多次。这是我的代码和我得到的输出。谢谢

package habeeb;

import java.util.*;

public class Habeeb {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] num = new int[30];
int i, count=0;

System.out.println("Enter the integers between 1 and 100" );

for( i=0; i<num.length; i++){
num[i]= input.nextInt();
if(num[i]==0)
break;
count++;
}

在这里调用函数

        Sorting(num, i, count);
}

public static void Sorting(int[] sort, int a, int con){
if (a<0) return;
/*am sorting the array here*/
Arrays.sort(sort);
int j, count=0;

for(j=0; j<con; j++){
if(sort[a]==sort[j])
count++;
}

System.out.println(sort[a]+" occurs "+count+" times");
Sorting(sort, a-1, con);
}
}

这是输出:

run:
Enter the integers between 1 and 100
2
5
4
8
1
6
0
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times

最佳答案

您的问题是数组的大小为 30,当您对它进行排序时,您没有分配给的所有值都等于 0,因此它们位于排序数组的前面。稍后在前 6 个数字中全部为 0,因此您的输出是正确的。

为了避免您遇到的问题,我建议您使用 ArrayList 而不是简单的数组,这样您就可以向其中动态添加元素。

关于java - 对数组进行排序并计算其元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15949499/

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