So I know that the java convention is to use ArrayList<> when it comes to expansions and many other applications. The typical array cannot expand. My java course is elementary so we are still reviewing over arrays right now. As much as I want to use an arraylist I cant. How do I make it to where I store only elements that satisfy the condition in my counter array?
public int[] above100Degrees()
{
int[] blazing = new int[temps.length];
for( int i = 0; i < temps.length; i++ )
{
if( temps[i] > 100 )
{
blazing[i] = temps[i];
}
}
return blazing;
}
Output
The temperature above 100 degrees is: 0 0 0 0 0 0 0 103 108 109
Just count how many elements match your filter first, then create the array, then populate it. It means you'll need to go through the array twice, but there are no really nice alternatives unless you want to end up creating multiple arrays. So something like:
public int[] above100Degrees() {
// First work out how many items match your filter
int count = 0;
// Are you allowed to use the enhanced for loop? It's not necessary, but it
// makes things simpler.
for (int temp : temps) {
if (temp > 100) {
count++;
}
}
// Create an array of the right size...
int[] ret = new int[count];
// ... and populate it.
int index = 0;
for (int temp : temps) {
if (temp > 100) {
ret[index++] = temp;
}
}
return ret;
}
See more on this question at Stackoverflow