I've been trying to solve this problem for quite some time now. I'm trying to display the min and max elements of an array, but the min always remains at 0. Here's the code that explains my issue:
public class ArrExs {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("enter the array capacity (min 1, max 20): ");
int n = input.nextInt();
while(n <= 0 || n > 20) {
System.out.print("enter a valid number and try again: ");
n = input.nextInt();
}
int[] nums = new int[n];
maxAndMin(nums);
}
public static void maxAndMin(int[] numbers) {
Scanner input = new Scanner(System.in);
System.out.println("enter your array elements: ");
int min = numbers[0];
int max = numbers[0];
for(int i = 0; i < numbers.length; i ) {
numbers[i] = input.nextInt();
max = (numbers[i] > max) ? numbers[i] : max;
min = (numbers[i] < min) ? numbers[i] : min;
}
System.out.print("min = " min ", max = " max);
}
}
The output:
enter the array capacity (min 1, max 20): 3
enter your array elements:
2
3
4
min = 0, max = 4
The min always remains at 0, I've tried to edit the code multiple times but I get the same result.
CodePudding user response:
I've encountered this problem before and watched a video where the instructor's logic is to set the "Min" and "Max" to the first number entered by the user. Then there comes the relational operator to decide which is minimum and maximum.
CodePudding user response:
The problem is on the line where you do int min = numbers[0];
because numbers
is an empty array (all of the values are 0). Since min
starts at 0 and nothing in the array is less than 0 then min will remain 0 forever.
Try making min
start as a high value such as int.MaxValue
and see if that fixes your problem.