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 "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)
I have tried using Integer.MAX_VALU
E 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("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
}
}