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 low low 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_VALUE and Integer.MIN_VALUE to start the high and low, orhigh and low, then process the array starting with the second element.int low = Integer.MAX_VALUE;
int high = Integer.MIN_VALUE;
P.S. You would find strange numbers printed, because you used characters instead of integers:
int[] numbs = { 2, 4, 2, 8, 4, 2, 5};
Also.. It is probably printing the ASCII representation... use actual integers (I'm not sure if your usage of chars was intentional).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With