import java.util.Scanner;
class ArrayMin {
public static void main(String args[]) {
@SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
int a[] = new int[10];
int max = a[0];
int min = a[0];
System.out.println("Enter elements of array :");
for (int i = 0; i < 10; i++) {
a[i] = scanner.nextInt();
if (i == 9)
break;
}
for (int i = 1; i < a.length; i++) {
if (a[i] > max)
max = a[i];
else if (a[i] < min)
min = a[i];
}
System.out.println("Result is max is :" + (max)); //if I input 1-10, output is 10
System.out.println("Result is min is :" + (min)); //whatever number I input the output is always 0
}
}
答案 0 :(得分:3)
声明数组时,它会初始化为全零。然后将min
分配给第一个元素,即零。假设所有值在分配后都是> = 0,因此min
仍然为零,但max
是正确的。
在 max
循环之后建立您的min
和for
,并为数组指定输入值。
for (int i = 0; i < 10; i++) {
a[i] = scanner.nextInt();
if (i == 9)
break;
}
// Moved HERE.
int max = a[0];
int min = a[0];
答案 1 :(得分:1)
替换它。
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
...
for (int i = 0; i < a.length; i++) {
if (a[i] > max)
max = a[i];
if (a[i] < min)
min = a[i];
}
...