I am trying to count occurrences of integers in an array. I would like to be able to modify the following loop that counts characters...
for (int i = 0; i < chars.length; i++)
counts[chars[i] - 'a']++;
I tried modifying it like this but getting an ArrayIndexOutOfBoundsException error...
for (int i = 0; i < ints.length; i++)
counts[ints[i] - '0']++;
Any ideas?
I have searched through many questions with similar titles but not in the fashion I need.
UPDATED
Here is my updated code. The user enters integers numbered 1 through 25. The program is supposed to count the occurrences of those integers using another array. I updated the code using...
counts[vals[i] - 1]++;
Which allows the program to compile. However, all the values of count are zeros.
UPDATED CODE...
import java.util.Scanner;
class CountIntOccurs
{
private static final int MAX_NUM_OF_VALUES = 200;
public static void main ( String [] args )
{
Scanner in = new Scanner( System.in );
int[] vals = new int[MAX_NUM_OF_VALUES];
int numOfVals = 0;
// Read and store values
System.out.println( "Enter integers <= 25, one per line, hit control-Z when done: " );
while ( in.hasNextLine() )
{
vals[numOfVals] = Integer.parseInt( in.nextLine() );
++numOfVals;
}
// Close application if no values entered
if ( numOfVals == 0 )
System.exit( 0 );
// declare counts array
int[] counts = new int[25];
System.out.println( counts.length );
//??????? For each integer in the array, count it
for (int i = 0; i < counts.length; i++){
counts[vals[i] - 1]++;
}
//display values enetered
for ( int i = 0; i < numOfVals; ++i )
{
System.out.println( vals[i] );
}
//?????? display counted integers????
for ( int i = 0; i < counts.length; ++i )
{
System.out.println( counts[i] );
}
}
}
Right now , what i need is to display the occurrences of the integers that are input. If I type in 1 1 2 2 2 the results should be 2 3 0 0 0 ... 0 .
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…