Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 计数数组中整数的出现次数_Java_Arrays_Counting - Fatal编程技术网

Java 计数数组中整数的出现次数

Java 计数数组中整数的出现次数,java,arrays,counting,Java,Arrays,Counting,我正在编写一个程序,计算数组中输入的整数的出现次数,例如,如果您输入1 1 2 1 3 5 2 3,程序将打印出不同的数字,后跟它们的出现次数,如下所示: Bag<Integer> bag = new TreeBag<Integer>(); for (int i = 0; i < numList.length; i++) { bag.add(numList[i]); } for (int uniqueNumber: bag.uniqueSet()) {

我正在编写一个程序,计算数组中输入的整数的出现次数,例如,如果您输入1 1 2 1 3 5 2 3,程序将打印出不同的数字,后跟它们的出现次数,如下所示:

Bag<Integer> bag = new TreeBag<Integer>();
for (int i = 0; i < numList.length; i++) {
    bag.add(numList[i]);
}
for (int uniqueNumber: bag.uniqueSet()) {
    System.out.println("Number " + uniqueNumber + " counted " + bag.getCount(uniqueNumber) + " times");
}
1发生5次, 2发生2次, 3发生2次, 5发生1次

它几乎完成了,除了一个我无法解决的问题:

import java.util.Scanner;
import java.util.Arrays;
public class CountOccurrences
{
   public static void main (String [] args)
   { 

    Scanner scan = new Scanner (System.in);

    final int MAX_NUM = 10;  

    final int MAX_VALUE = 100;

    int [] numList;

    int num;

    int numCount;

    int [] occurrences; 

    int count[];

    String end;

    numList = new int [MAX_NUM];

    occurrences = new int [MAX_NUM];

    count = new int [MAX_NUM];

 do
  {
     System.out.print ("Enter 10 integers between 1 and 100: ");

     for (num = 0; num < MAX_NUM; num++)
     {
        numList[num] = scan.nextInt();
     }

     Arrays.sort(numList);

     count = occurrences (numList); 

     System.out.println();   

     for (num = 0; num < MAX_NUM; num++)
     {
        if (num == 0)
        {
           if (count[num] <= 1)
              System.out.println (numList[num] + " occurs " + count[num] + " time");

           if (count[num] > 1)
              System.out.println (numList[num] + " occurs " + count[num] + " times");
        } 

        if (num > 0 && numList[num] != numList[num - 1])
        {
           if (count[num] <= 1)
              System.out.println (numList[num] + " occurs " + count[num] + " time");

           if (count[num] > 1)
              System.out.println (numList[num] + " occurs " + count[num] + " times");
        }   
     }          

     System.out.print ("\nContinue? <y/n> ");
     end = scan.next(); 

  } while (!end.equalsIgnoreCase("n"));
}


 public static int [] occurrences (int [] list)
 {
      final int MAX_VALUE = 100;

      int num;

      int [] countNum = new int [MAX_VALUE];

      int [] counts = new int [MAX_VALUE];

      for (num = 0; num < list.length; num++)
  {
     counts[num] = countNum[list[num]] += 1;
  }

  return counts;
 } 
}
import java.util.Scanner;
导入java.util.array;
公共类计数事件
{
公共静态void main(字符串[]args)
{ 
扫描仪扫描=新扫描仪(System.in);
最终整数最大值=10;
最终int最大值=100;
int[]numList;
int-num;
国际计算;
int[]个事件;
整数计数[];
弦端;
numList=新整数[MAX_NUM];
发生次数=新整数[MAX_NUM];
计数=新整数[MAX_NUM];
做
{
System.out.print(“输入1到100之间的10个整数:”;
对于(num=0;num0&&numList[num]!=numList[num-1])
{
如果(计数[num]1)
System.out.println(numList[num]+“发生”+计数[num]+“次数”);
}   
}          
System.out.print(“\n是否继续?”);
end=scan.next();
}而(!end.equalsIgnoreCase(“n”));
}
公共静态int[]事件(int[]列表)
{
最终int最大值=100;
int-num;
int[]countNum=新的int[MAX_值];
int[]计数=新的int[最大值];
对于(num=0;num
我遇到的问题是,无论'num'的当前值是什么,'count'只打印出1,而问题不在于计算出现次数的方法,因为当您在变量的位置输入数字时,值会发生变化

有没有什么方法可以改变它,这样它就可以正确地打印出事件,或者我应该尝试其他方法? 解决方案越简单越好,因为我还没有讨论过一维数组


谢谢你的帮助

您可以从初始化一个介于最小值和最大值之间的值数组开始。然后,当该值出现时,您可以添加到数组的每个元素1。大概

Scanner scan = new Scanner(System.in);
final int MAX_NUM = 10;
final int MAX_VALUE = 100;
final int MIN_VALUE = 1;
final int SIZE = MAX_VALUE - MIN_VALUE;
int[] numList = new int[SIZE];
System.out.printf("Enter %d integers between %d and %d:%n", 
        MAX_NUM, MIN_VALUE, MAX_VALUE);
for (int i = 0; i < MAX_NUM; i++) {
  System.out.printf("Please enter number %d: ", i + 1);
  System.out.flush();
  if (!scan.hasNextInt()) {
    System.out.printf("%s is not an int%n", scan.nextLine());
    i--;
    continue;
  }
  int v = scan.nextInt();
  if (v < MIN_VALUE || v > MAX_VALUE) {
    System.out.printf("%d is not between %d and %d%n", 
            v, MIN_VALUE, MAX_VALUE);
    continue;
  }
  numList[v - MIN_VALUE]++;
}
boolean first = true;
for (int i = 0; i < SIZE; i++) {
  if (numList[i] > 0) {
    if (!first) {
      System.out.print(", ");
    } else {
      first = false;
    }
    if (numList[i] > 1) {
      System.out.printf("%d occurs %d times", 
              i + MIN_VALUE, numList[i]);
    } else {
      System.out.printf("%d occurs once", i + MIN_VALUE);
    }
  }
}
System.out.println();
Scanner scan=新的扫描仪(System.in);
最终整数最大值=10;
最终int最大值=100;
最终int最小值=1;
最终整数大小=最大值-最小值;
int[]numList=新的int[SIZE];
System.out.printf(“输入%d和%d之间的%d个整数:%n”,
最大值、最小值、最大值);
对于(int i=0;iMAX|u值){
System.out.printf(“%d不在%d和%d之间%n”,
v、 最小值、最大值);
继续;
}
numList[v-MIN_值]+;
}
布尔值优先=真;
对于(int i=0;i0){
如果(!第一个){
系统输出打印(“,”);
}否则{
第一个=假;
}
if(numList[i]>1){
System.out.printf(“%d次出现%d次”,
i+MIN_值,numList[i]);
}否则{
System.out.printf(“%d出现一次”,i+MIN\u值);
}
}
}
System.out.println();

1另请参见。

尝试HashMap。对于这类问题,哈希是非常有效和快速的

我编写了这个函数,它接受数组并返回一个HashMap,其键是数字,值是该数字的发生率

public static HashMap<Integer, Integer> getRepetitions(int[] testCases) {    
    HashMap<Integer, Integer> numberAppearance = new HashMap<Integer, Integer>();

    for(int n: testCases) {
        if(numberAppearance.containsKey(n)) {
            int counter = numberAppearance.get(n);
            counter = counter+1;
            numberAppearance.put(n, counter);
        } else {
            numberAppearance.put(n, 1);
        }
    }
    return numberAppearance;
}
publicstatichashmap getRepetitions(int[]testCases){
HashMap numberAppearance=新HashMap();
for(int n:testCases){
如果(数字显示容器(n)){
int counter=numberapearance.get(n);
计数器=计数器+1;
数字显示(n,计数器);
}否则{
数显式(n,1);
}
}
返回数显示;
}
现在迭代hashmap并打印如下数字:

HashMap<Integer, Integer> table = getRepetitions(testCases);

for (int key: table.keySet()) {
        System.out.println(key + " occur " + table.get(key) + " times");
}
HashMap table=getRepetitions(testCases);
for(int键:table.keySet()){
System.out.println(键+“发生”+表.get(键)+“次数”);
}
输出:


我认为如果使用这种方法,可以大大简化代码。您仍然需要修改以包括
MAX\u NUM
MAX\u值

public static void main(String[] args) {

    Integer[] array = {1,2,0,3,4,5,6,6,7,8};
    Stack stack = new Stack();

    Arrays.sort(array, Collections.reverseOrder());

    for(int i : array){
        stack.push(i);
    }

    int currentNumber = Integer.parseInt(stack.pop().toString()) , count = 1;

    try {
        while (stack.size() >= 0) {
            if (currentNumber != Integer.parseInt(stack.peek().toString())) {
                System.out.printf("%d occurs %d times, ", currentNumber, count);
                currentNumber = Integer.parseInt(stack.pop().toString());
                count = 1;
            } else {
                currentNumber = Integer.parseInt(stack.pop().toString());
                count++;
            }
        }
    } catch (EmptyStackException e) {
         System.out.printf("%d occurs %d times.", currentNumber, count);
    }
}

我会用一个袋子,一个可以计算物品出现在收藏中次数的收藏。apachecommons有一个它的实现。这是他们的,这是一个

你可以这样做:

Bag<Integer> bag = new TreeBag<Integer>();
for (int i = 0; i < numList.length; i++) {
    bag.add(numList[i]);
}
for (int uniqueNumber: bag.uniqueSet()) {
    System.out.println("Number " + uniqueNumber + " counted " + bag.getCount(uniqueNumber) + " times");
}

我要说的是,我花了一段时间才弄清楚
count
countNum
这两个变量代表什么,可能需要一些注释。但最后我发现了错误

假设输入的十个数字是:
5,6,7,8,5,6,7,8,5,6

排序后,
numList
是:
5,5,5,6,6,7,7,8

executions()返回的数组
count
应该是:
[1,2,3,1,2,3,1,2]

实际上,此结果数组中唯一有用的数字是:

count[2]: 3     count number for numList[2]: 5
count[5]: 3     count number for numList[5]: 6
count[7]: 2     count number for numList[7]: 7
count[9]: 2     count number for numList[9]: 8
其他数字,如
1,2
之前的前两个数字
3
,仅用于增量计算总和,对吗?因此,您的循环逻辑应更改如下:

  • 删除第一个
    如果
    代码块:

    if (num == 0)
    {
       if (count[num] <= 1)
          System.out.println (numList[num] + " occurs " + count[num] + " time");
    
       if (count[num] > 1)
          System.out.println (numList[num] + " occurs " + count[num] + " times");
    } 
    
  • 在这之后,您的代码应该可以正常工作

    顺便说一句,
    if ((num + 1) == MAX_NUM || numList[num] != numList[num + 1]) {
        ......
    }