[英]Java array minimum element within for-loop
OK, I have been at it for a long time now. 好的,我已经很长时间了。 I have looked after similar problems here in stack-overflow and I still can't make it work. 我在这里已经解决了堆栈溢出中的类似问题,但仍然无法使其正常工作。 I need to find the maximum values within an array and minimum values. 我需要找到数组中的最大值和最小值。 Trying to find the minimum is the problem. 试图找到最小值是问题所在。 I have literately tried everything from writing separate methods and so on and still the output in 0. Here is what I have tried: 我已经尝试过从编写单独的方法开始的所有操作,等等,仍然将输出设置为0。这是我尝试过的:
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
}
}
When you declare your array, it's initialized to all zeroes. 声明数组时,它会初始化为全零。 Then you assign the min
to your first element, which is zero. 然后,将min
分配给第一个元素,即零。 Presumably all values are >= to 0 once they're assigned, so the min
is still zero, but the max
is correct. 假定所有值在分配后都> =到0,因此min
仍为零,但max
正确。
Establish your max
and min
after the for
loop where you assign input values to the array. 在for
循环后建立max
和min
,在其中将输入值分配给数组。
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];
Replace this. 更换它。
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];
}
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.