每个任意数量的整数的出现(Java) - 构建不运行的类

时间:2015-12-02 05:56:38

标签: java

我正在进行化妆任务,读取0到100(包括0和100)范围内的任意数量的整数,并计算每次输入的出现次数。

虽然我确信IntegerCount在其当前状态下正常工作,但我不知道如何在主函数中实现它。在构建期间,我一直输入整数但是没有得到来自account,getOc​​curance或print对象的结果,除非我尝试为异常添加一个超出范围的整数。我错过了什么吗?

主类:

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        IntegerCount intCount = new IntegerCount();
        int submit;
        System.out.println("Type Integers: ");
        while (input.hasNext()) {
            submit = input.nextInt();
            intCount.account(submit); // Should be where the integers are being
                                        // sent to the IntegerCount class
        }
        intCount.print();
    }
}

IntegerCount类:

public class IntegerCount {
    private int max = 100;
    int[] integer = new int[max];

    public void account(int val) {
        integer[val] = integer[val] - 1;
    }

    public int getOccurrences(int val) {
        return integer[val];
    }

    public void print() {
        for (int i = 0; i < integer.length; i++) {
            if (integer[i] != 0) {
                System.out.println("number of occurrences of " + i + "occurs " + integer[i] + "times");
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我看到你的while (input.hasNext())进入无限循环阅读整数。我建议你首先读取0到100范围内的整数,然后相应地计算它们。我已按如下方式修改了您的main方法,以计算numberOfIntegersToCount整数的出现次数:

import java.util.Scanner;


public class Main {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        IntegerCount intCount = new IntegerCount();

        // number of integers to count in the range of 0 to 100
        int numberOfIntegersToCount = input.nextInt();

        System.out.println("Type Integers: ");

        // loop until all integers are read
        while (numberOfIntegersToCount > 0){
            int submit = input.nextInt();
            intCount.account(submit); //Should be where the integers are being sent to the IntegerCount class
            numberOfIntegersToCount--;
        }
        intCount.print();

    }
}

account实际上是负数。我还修改了account方法如下:

public void account(int val) {
     integer[val] = integer[val] + 1;
} 

既然你说:

  

0到100(含)

您当前的IntegerCount代码不适用于输入100.对于100 ArrayIndexOutOfBoundsException将被抛出。