【发布时间】:2020-10-14 06:21:41
【问题描述】:
我已经编写了下面的代码,并且附加了 cmets。该应用程序将读取用户输入的七个整数。然后应用程序打印出这七个值中每一个的出现次数。
当我输入整数时程序崩溃:1 2 3 1 2 3 100
Error: Exception in thread "main" `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)
我尝试在代码中使用Integer.MAX_VALUE 来解决问题。我知道我的数组应该有 7 个而不是 100 个。并且输入不应该影响程序。我难住了。代码如下:
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("Student's Copy");
Scanner input = new Scanner(System.in);
System.out.println("Enter seven numbers: ");
/**
* 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 < 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 < 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 < count.length; i++){
if(count[i] > 0 && count[i] == 1){
System.out.printf("Number %d occurs %d time.\n",i, count[i]);
}
else if(count[i] >=2){
System.out.printf("Number %d occurs %d times.\n",i, count[i]);
}
}//end of for loop
}
}
【问题讨论】:
-
你的逻辑在这里失败 tempHold = number[i];计数[温度保持]++;您将数组值作为索引。这意味着如果您要添加一个大于 7 的数字。您的代码将给出您现在得到的异常。
标签: java arrays loops findbugs find-occurrences