I’m trying to find the high and low number in an array, but I’m not sure why my codes not working correctly. It’s giving me the output of 0 and 56. I understand why it’s giving the 0, but where did the 56 come from?
package test;
public class Test {
public static void main(String[] args) {
int[] numbs = { '2', '4', '2', '8', '4', '2', '5'};
int count = 0;
int low = 0;
int high = 0;
while(count < numbs.length)
{
if(numbs[count]< low) {
low = numbs[count];
}
if(numbs[count]> high) {
high = numbs[count];
}
count++;
}
System.out.println(low);
System.out.println(high);
}
}
You need to start the
lowlow enough; currently, you start it at zero – too low to “catch” the lowest element of the array.There are two ways to deal with this:
Integer.MAX_VALUEandInteger.MIN_VALUEto start thehighandlow, orhighandlow, then process the array starting with the second element.P.S. You would find strange numbers printed, because you used characters instead of integers: