gpt4 book ai didi

java - 阵列频率

转载 作者:行者123 更新时间:2023-12-01 13:48:01 24 4
gpt4 key购买 nike

我正在尝试用 50 个整数值初始化一个数组,并计算 10 .. 19 范围内数字的频率。 。我认为问题出在代码的底部。

import java.util.Scanner;
public class Ex1partA {
public static void main(String[] args) {
Scanner kbin = new Scanner(System.in);

int list[]=new int[50];
int i=0;

System.out.print("\n\tInput numbers from 10 to 19: \n");

while (i < 50) {
int value = kbin.nextInt();
if (value >= 10 & value <= 19) {
list[i] = value;
i++;
} else {
System.out.println("!! Bad number !!");
}
}

for (int value : list) {
System.out.println("" + value);
}
}
}

最佳答案

I'm trying to initialize an array with 50 integer values and compute the frequency of numbers in the range of 10 .. 19.

要计算频率,最好将所有数字放入 List 中,并使用 Collections.Frequency 计算频率

  List<Integer> freqList=new ArrayList<Integer>();
// Add numebers to this list.

for (int i = 10; i <20; i++) {
int freq=Collections.frequency(freqList, i);
// This will return frequency of number

System.out.println(i+" "+freq);
}

关于java - 阵列频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20198658/

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