问题
So I'm trying to find a min and max of an array which are put in by the user.
This is my code
public static void main(String[] args) {
int[] a = new int[args.length];
for (int i = 0; i < args.length; i++) {
a[i] = Integer.parseInt(args[i]);
int max = a[0];
for (int j = 1; j < args.length; j++) {
if (a[j] > max) {
max = a[j];
}
}
System.out.println("the maximum value of the array is " + max);
}
}
But the output I am getting is every single number I have put in. What is my mistake here?
回答1:
Let's go through the process. Because this is an int array the values are initialized to 0
. In the first for loop we assign the first int to a[0]
. Then in the second for loop we check every value in the array if it is maximal (so checking the first value against a load of zeros) then you exit the nested for loop and print the statement (with the value of a[0]
, if it was positive).
Now we go through the second cycle of the outer loop, if this was bigger again this value will be printed, otherwise the first value will be reprinted (was your array in ascending order by any chance?) and so on for each value.
As was commented, a single loop would be enough, and ensure your print statement is outside of the outer for loop
Hope this helps
回答2:
You only need one loop to check through the array.
Below is an example
int[] arr = {2, 3, 1, 6, 4, 7, 8, 5};
int max = arr[0];
int min = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
}
回答3:
You aren't fully populating the array before you search for more values. You shouldn't be searching forward. Also, you shouldn't print until after you determine the min
and max
. If you're using Java 8+, this problem is much easier to solve; map the args to int(s) and get the summary statistics. Like,
IntSummaryStatistics stats = Stream.of(args).mapToInt(Integer::parseInt)
.summaryStatistics();
System.out.printf("The minimum value is %d%n", stats.getMin());
System.out.printf("The maximum value is %d%n", stats.getMax());
or fixing your current code, declare min
and max
outside the loop. Update them on each value. Then display the result. Like,
int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
int[] a = new int[args.length];
for (int i = 0; i < args.length; i++) {
a[i] = Integer.parseInt(args[i]);
max = Math.max(a[i], max);
min = Math.min(a[i], min);
}
System.out.printf("The minimum value is %d%n", min);
System.out.printf("The maximum value is %d%n", max);
回答4:
You do not need loops at all, try Streams:
int[] a = { 1, 2, 3, 4, 5 };
int max = Arrays.stream(a).max().getAsInt();
int min = Arrays.stream(a).min().getAsInt();
System.out.println("max value is: " + max);
System.out.println("min value is: " + min);
Output is :
max value is: 5
min value is: 1
来源:https://stackoverflow.com/questions/47383316/finding-a-minimum-and-maximum-value-in-an-array