Java - 在数组中查找高和低数字

Phi*_*ego 3 java

我试图在数组中找到高低数字,但我不确定为什么我的代码无法正常工作.它给了我0和56的输出.我理解为什么它给0,但56来自哪里?

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);           

    }
}
Run Code Online (Sandbox Code Playgroud)

das*_*ght 7

你需要开始low足够低; 目前,你从零开始 - 太低而不能"捕获"数组的最低元素.

有两种方法可以解决这个问题:

  • 使用Integer.MAX_VALUEInteger.MIN_VALUE启动highlow,或
  • 使用初始元件阵列的开始两个highlow,则过程开始与所述第二元件的阵列.

int low = Integer.MAX_VALUE;
int high = Integer.MIN_VALUE;
Run Code Online (Sandbox Code Playgroud)

PS你会发现打印出奇怪的数字,因为你使用的是字符而不是整数:

int[] numbs = { 2, 4, 2, 8, 4, 2, 5};
Run Code Online (Sandbox Code Playgroud)