统计数组中七个整数的出现次数

huangapple go评论71阅读模式
英文:

Count Occurrences of Seven Integers in Array

问题

我已经写好了以下的代码,并且附上了注释。该程序用于读取用户输入的七个整数,然后打印出每个值出现的次数。

当我输入整数 1 2 3 1 2 3 100 时,程序崩溃了:

错误线程 "main" 中的异常 "java.lang.ArrayIndexOutOfBoundsException: 100" 位于 u7a1_numofoccurrinsevenints.U7A1_NumOfOccurrInSevenInts.main(U7A1_NumOfOccurrInSevenInts.java:78)
/Users/davramirez/Library/Caches/NetBeans/8.2/executor-snippets/run.xml:53: Java 返回了1
构建失败总时间5秒

我尝试在代码中使用 Integer.MAX_VALUE 来解决问题。我知道我的数组应该有7个元素,而不是100个。并且输入不应该影响程序。我被卡住了。以下是代码:

package u7a1_numofoccurrinsevenints;

// 初始化扫描工具
import java.util.Scanner;

/**
 *
 * 作者:davramirez
 */
public class U7A1_NumOfOccurrInSevenInts {

    /**
     * @param args 命令行参数
     */
    public static void main(String[] args) {
        // TODO 代码应用逻辑在这里


        /**
         * 调用扫描器方法来接受用户输入。
         * 打印学生副本。
         * 打印输入七个数字的说明
         */
        System.out.println("学生副本");
        Scanner input = new Scanner(System.in);
        System.out.println("输入七个数字:");
        /**
         * 初始化数字和计数数组
         * 数组数字接受来自用户的整数值。
         * 数组计数作为程序中的计数器
         * 声明计数器变量为整数。
         * 计数器用于 for 循环中的计数,以便在达到7时停止
         */
        int [] number = new int[7]; 
        int [] count = new int[7];
        int counter = 0;

        /**
         * 声明变量 i 为整数
         * 声明变量 tempHold 为整数,初始值为零
         * 变量 tempHold 临时存储值
         * 数组数字在特定索引处的值暂存到 tempHold 变量中
         */
        int i, tempHold = 0;


        /**
         * 循环填充数组数字从用户输入中获得
         * 使用 counter++ 计数数组的七个值
         * if 语句循环,直到计数器达到七
         * 当计数器达到七时,程序退出
         * 将用户输入存储到 number[] 数组中
         */

        for(i = 0; i < number.length; i++){
            number[i] = input.nextInt();
            counter++;

            if(counter == 7){
                break;
            }
        } // 循环结束

        /**
         * 循环传递数组的值
         * 值存储在 tempHold 变量中
         * tempHold 变量用作索引值
         * 计数数组跟踪每个整数的总出现次数。
         */

        for(i = 0; i < number.length; i++){
                tempHold = number[i];
                count[tempHold]++;
            }// 循环结束

         /**
         * 循环打印数字加上出现次数
         * if 语句检查整数是否重复
         * 如果不重复,程序打印出发生的次数
         * 否则使用 times。这样打印出语法上正确的结果。
         */
        for(i = 1; i < count.length; i++){

            if(count[i] > 0 && count[i] == 1){
             System.out.printf("数字 %d 出现 %d 次。\n", i, count[i]);
             }
            else if(count[i] >= 2){
                System.out.printf("数字 %d 出现 %d 次。\n", i, count[i]);
            }
         } // 循环结束
    
    } 
}
英文:

I have written the code below and it has comments attached. The application is to read seven integers entered by the user. The application then prints out the number of occurrences of each of the seven values.

The program crashes when I enter in the integers: 1 2 3 1 2 3 100

Error: Exception in thread &quot;main&quot; `java.lang.ArrayIndexOutOfBoundsException: 100` at u7a1_numofoccurrinsevenints.U7A1_NumOfOccurrInSevenInts.main(U7A1_NumOfOccurrInSevenInts.java:78)
/Users/davramirez/Library/Caches/NetBeans/8.2/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 5 seconds)

I have tried using Integer.MAX_VALUE in the code to fix the problem. I know that my arrays should have 7 instead of 100. And that the input should not affect the program. I am stumped. The code is below:

package u7a1_numofoccurrinsevenints;
// Initialize scanner untility 
import java.util.Scanner;
/**
*
* @author davramirez
*/
public class U7A1_NumOfOccurrInSevenInts {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
/**
* Call scanner method to take user input.
* Print out student copy.
* Print out instructions to enter seven numbers
*/
System.out.println(&quot;Student&#39;s Copy&quot;);
Scanner input = new Scanner(System.in);
System.out.println(&quot;Enter seven numbers: &quot;);
/**
* Initialize arrays number and count
* Array number takes integer value from user.
* Array count servers as counter in the program
* Declare variable counter as integer.
* Counter serves as counter in for loop to stop at 7
*/
int [] number = new int[7]; 
int [] count = new int[7];
int counter = 0;
/**
* Declare variable i as integer
* Declare variable tempHold as the integer with value of zero
* Variable tempHold temporarily stores value
* of the array number at a specific index
*/
int i, tempHold = 0;
/**
* For loop that populates array number from  user input
* Counter++ used to count seven values of the array
* If statement that loops for counter to reach seven
* When seven reach the program exits
* stores user input to  number[] array
*/
for(i=0; i &lt; number.length; i++){
number[i] = input.nextInt();
counter++;
if(counter == 7){
break;
}
} // End of for loop
/**
* For loop that passes value of array
* The value is stored in the tempHold variable
* tempHold variable used as index value
* Count array tracks total occurrences of each integer.
*/
for(i = 0; i &lt; number.length; i++){
tempHold = number[i];
count[tempHold]++;
}// End of for looop
/**
* For loop prints out number plus the occurrence
* If statement that checks with the integer is repeated
* If the does not repeat the program prints time occurred
* Else it uses times. This prints out grammatically correct results.
*/
for(i=1; i &lt; count.length; i++){
if(count[i] &gt; 0 &amp;&amp; count[i] == 1){
System.out.printf(&quot;Number %d occurs %d time.\n&quot;,i, count[i]);
}
else if(count[i] &gt;=2){
System.out.printf(&quot;Number %d occurs %d times.\n&quot;,i, count[i]);
}
}//end of for loop
} 
}

答案1

得分: 2

可以通过使用**HashMap&lt;Integer, Integer&gt;**来实现相同的功能如下所示

    package u7a1_numofoccurrinsevenints;
    
    import java.util.HashMap;
    import java.util.Scanner;
    
    public class U7A1_NumOfOccurrInSevenInts  {
    
    	public static void main(String[] args) {
    		Scanner input = new Scanner(System.in);
    		int[] inputArray = new int[7];
    		System.out.print("Enter seven numbers: ");
    		for (int i = 0; i < 7; i++) {
    			inputArray[i] = input.nextInt();
    		}
    
    		HashMap<Integer, Integer> numberCountMap = new HashMap<>();
    		for(int element : inputArray){
    			numberCountMap.put(element, (numberCountMap.containsKey(element)) ? numberCountMap.get(element) + 1 : 1);
    		}
    		numberCountMap.forEach((key, value) -> System.out.println("Number " + key + " occurs " + value + " times."));
    	}
    }
英文:

You can do the same By using HashMap<Integer, Integer> as shown below.

package u7a1_numofoccurrinsevenints;
import java.util.HashMap;
import java.util.Scanner;
public class U7A1_NumOfOccurrInSevenInts  {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] inputArray = new int[7];
System.out.print(&quot;Enter seven numbers: &quot;);
for (int i = 0; i &lt; 7; i++) {
inputArray[i] = input.nextInt();
}
HashMap&lt;Integer, Integer&gt; numberCountMap = new HashMap&lt;&gt;();
for(int element : inputArray){
numberCountMap.put(element, (numberCountMap.containsKey(element)) ? numberCountMap.get(element) + 1 : 1);
}
numberCountMap.forEach((key, value) -&gt; System.out.println(&quot;Number &quot; + key + &quot; occurs &quot; + value + &quot; times.&quot;));
}
}

答案2

得分: 1

好的,以下是翻译好的内容:

问题出在你尝试访问 count[] 数组中的索引 100,但该数组的大小仅为 7
因此,这行代码有问题:count[tempHold]++;

总体而言,你的方法过于复杂,无法正常工作。
在这个网站上已经有很多更好、更简洁的解决方法被发布了很多次,所以我不会在这里为你的问题提供详细的代码片段。但你可以查看这个解决方案,其中也包含了解释。

编辑:

显然,你基本上是参考了之前一个问题的这个回答,并稍微进行了修改。如果你继续往下滚动,你会找到另一个更合适的答案。

英文:

Well, your issue occurs because you are trying to access the index 100 in your count[] array, which is only of size 7.
So, this line is faulty: count[tempHold]++;.

Altogether, your approach is overly complicated and can't work out.
Better and cleaner ways to do this have been posted thousand of times on this site, so I won't post a detailed snippet for your issue here. But you can check out this solution, which also contains an explanation.

Edit:

Apparently you just basically took this response from a previous quesiton and slightly modified it. If you scrolled further down, you would have found a more suitable answer aswell.

答案3

得分: 0

你的导师是否提到过单一职责原则或测试驱动开发?现在是讨论这些内容的好时机。

你的 main() 做了太多的事情:将用户输入引导到数组中,处理该数组并报告结果。我建议你至少创建一个独立的“方法”,一个接受整数数组并计算数组中数字出现次数的函数。

我看到你正在使用 NetBeans,明智的选择。这意味着你可以访问 JUnit 和 TestNG。你可以使用其中一个测试框架来帮助你使程序更模块化,更容易测试。这也意味着当出现问题时更容易定位问题的源头。

采纳 Trushit 的建议,使用 HashMap<Integer, Integer>,为一个函数创建存根,该函数接受一个整数数组并返回一个 HashMap<Integer, Integer>

    // 用于失败第一个测试的存根
    static HashMap<Integer, Integer> countOccur(int[] numbers) {
        HashMap<Integer, Integer> map = new HashMap<>();
        map.put(0, 0);
        return map;
    }

接下来,将鼠标放在声明类("public class U7A1_NumOfOccurrInSevenInts")的那一行,并单击取代行号的灯泡图标。选择创建一个新的 JUnit 测试类。

有时候 NetBeans 会生成好的测试,有时候不会。但如果没有警告,暂时可以忽略那些测试。在测试类中,添加这个测试:

    @Test
    public void testAllNumbersTheSame() {
        int[] numbers = {10, 10, 10, 10, 10, 10, 10};
        HashMap<Integer, Integer> expected = new HashMap<>();
        expected.put(10, 7); // 十出现了七次
        HashMap<Integer, Integer> actual = countOccur(numbers);
        assertEquals(expected, actual);
    }

(你可能需要使用 countOccur() 的全限定名,或者添加一个静态导入)

运行测试(Run > Test File),或使用键盘快捷键(在 Windows 上是 Ctrl-F6)。这个测试应该会失败。通过对 countOccur() 进行一个简单的更改来使其通过:

        map.put(10, 7);

现在编写另一个预期结果不同的测试。使用你的示例:

    @Test
    public void testDifferentNumbers() {
        int[] numbers = {1, 2, 3, 1, 2, 3, 100};
        HashMap<Integer, Integer> expected = new HashMap<>();
        expected.put(1, 2);
        expected.put(2, 2);
        expected.put(3, 2);
        expected.put(100, 1);
        HashMap<Integer, Integer> actual = countOccur(numbers);
        assertEquals(expected, actual);
    }

当然,这个测试会失败(之前的测试应该还是会通过的)。关于如何使其通过,可以参考 Trushit 的回答(需要 Java 8 或更高版本)。

英文:

Has your instructor mentioned the single responsibility principle or test-driven development? This assignment is as good a time as any to discuss those.

Your main() is doing too much: shepherding input from the user into an array, processing that array and reporting the results. I recommend you create at least one separate "method," a function that takes in an array of integers and counts occurrences of numbers in that array.

I see you're using NetBeans. Wise choice. That means you have access to JUnit and TestNG. You can use one of those testing frameworks to help you make your program more modular and easier to test. That also means easier to pinpoint the source of the problem when something goes wrong.

Taking Trushit's idea to use HashMap&lt;Integer, Integer&gt;, make a stub for a function that takes in an array of integers and returns a HashMap&lt;Integer, Integer&gt;.

    // STUB TO FAIL THE FIRST TEST
static HashMap&lt;Integer, Integer&gt; countOccur(int[] numbers) {
HashMap&lt;Integer, Integer&gt; map = new HashMap&lt;&gt;();
map.put(0, 0);
return map;
}

Next, put your mouse on the line declaring the class("public class U7A1_NumOfOccurrInSevenInts") and click on the lightbulb that replaces the line number. Select the option to create a new JUnit test class.

Sometimes NetBeans comes up with good tests, sometimes not. But if there are no warnings, you can simply ignore those tests for the time being. In the test class, add this test:

    @Test
public void testAllNumbersTheSame() {
int[] numbers = {10, 10, 10, 10, 10, 10, 10};
HashMap&lt;Integer, Integer&gt; expected = new HashMap&lt;&gt;();
expected.put(10, 7); // Ten occurs seven times
HashMap&lt;Integer, Integer&gt; actual = countOccur(numbers);
assertEquals(expected, actual);
}

(You might need to use the fully qualified name for countOccur() or add a static import)

Run the test (Run > Test File) or use the keyboard shortcut (Ctrl-F6 on Windows). This test should fail. Make it pass with a simple change to countOccur():

        map.put(10, 7);

Now write that expects different results. To use your example,

    @Test
public void testDifferentNumbers() {
int[] numbers = {1, 2, 3, 1, 2, 3, 100};
HashMap&lt;Integer, Integer&gt; expected = new HashMap&lt;&gt;();
expected.put(1, 2);
expected.put(2, 2);
expected.put(3, 2);
expected.put(100, 1);
HashMap&lt;Integer, Integer&gt; actual = countOccur(numbers);
assertEquals(expected, actual);
}

This test will fail, of course (the previous test should still pass). Refer to Trushit's answer for one possible way to make it pass (requires Java 8 or later).

答案4

得分: 0

public class U7A1_NumOfOccurrInSevenInts {

    public static void main(String[] args) {
        System.out.print("教师副本");
        Scanner in = new Scanner(System.in);
        int[] arr = new int[7];
        System.out.print("输入七个数字:");
        for (int i = 0; i < arr.length; ++i) {
            arr[i] = in.nextInt();  // 将7个数字读入数组
        }
        for (int i = 0; i < arr.length; ++i) {   // 遍历所有元素
            if (!checkIfElementAlreadyExists(arr, i)) {  // 如果此元素之前未在数组中出现过
                System.out.printf("数字 %d 出现 %d 次。\n", arr[i],
                    count(arr, arr[i]));  // 则打印数字及其在数组中出现的次数
            }
        }
    }

    public static int count(int[] arr, int num) {
        int count = 0;
        for (int i = 0; i < arr.length; ++i) {   // 遍历数组中的所有元素
            if (arr[i] == num) { // 如果找到 num,增加计数
                count++;    // 增加计数
            }
        }
        return count;   // 返回数组中 num 出现的次数
    }

    public static boolean checkIfElementAlreadyExists(int[] arr, int index) {
        for (int i = 0; i < index; ++i) {    // 遍历数组中的所有元素
            if (arr[i] == arr[index]) {  // 如果索引处的元素已经存在于数组中
                return true;    // 则返回 true
            }
        }
        return false;   // 如果索引处的元素之前未出现过,则返回 false
    }
}
英文:
public class U7A1_NumOfOccurrInSevenInts {

    public static void main(String[] args) {
        System.out.print(&quot;Teacher&#39;s Copy&quot;);
        Scanner in = new Scanner(System.in);
        int[] arr = new int[7];
        System.out.print(&quot;Enter seven numbers: &quot;);
        for (int i = 0; i &lt; arr.length; ++i) {
            arr[i] = in.nextInt();  // read 7 numbers into array
        }
        for (int i = 0; i &lt; arr.length; ++i) {   // go through all elements
            if (!checkIfElementAlreadyExists(arr, i)) {  // if this element did not already appear before in the array
                System.out.printf(&quot;Number %d occurs %d times.\n&quot;, arr[i],
                    count(arr, arr[i]));  // then print the number and the number of time it occurs in the array
            }
        }
    }

    public static int count(int[] arr, int num) {
        int count = 0;
        for (int i = 0; i &lt; arr.length; ++i) {   // go through all elements in array
            if (arr[i] == num) { // if num is found, increase count
                count++;    // increment count
            }
        }
        return count;   // return the count of number of occurrences of num in array
    }

    public static boolean checkIfElementAlreadyExists(int[] arr, int index) {
        for (int i = 0; i &lt; index; ++i) {    // go through all elements in array
            if (arr[i] == arr[index]) {  // if item in index already exists in the array
                return true;    // then return true
            }
        }
        return false;   // if element at index does not previously occur, then return false
    }
}

huangapple
  • 本文由 发表于 2020年10月14日 14:21:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/64347667.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定