Why it does not work
You read day[0]
before you assign it any value.
Your code
int[] day = new int[x];
int minValue = day[0];
int maxValue = day[0];
is equivalent to
int[] day = new int[x];
int minValue = 0;
int maxValue = 0;
See https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.12.5:
Each ... array component is initialized with a default value when it is created.
For type int, the default value is zero, that is, 0.
You code works for max
only by accident :) Try entering only negative values to the input and your max
will also give only 0
.
How to fix it
It is highly recommendable to split the computational part from the input/output. Java cannot easily return two values from a method. You may implement two separate methods, for max
and min
separately, or you may return the two values in an ad-hoc created Tuple object.
The input/output part:
final Scanner sc = new Scanner(System.in);
final int numberOfValues = sc.nextInt();
final int[] values = new int[numberOfValues];
for (int i = 0; i < numberOfValues; i++) {
values[i] = sc.nextInt();
}
System.out.println(minValue(values));
System.out.println(maxValue(values));
And the computing part (look at the for-each loop https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html):
public int minValue(int[] array) {
int min = Integer.MAX_VALUE;
for (int value : array) {
if (value < min) {
min = value;
}
}
}
Analogically for maxValue()
, you will now easily do it on your own.
Your program still needs some error handling, such as when the user provides inconsistent input.
You should get the habit of splitting the computational and presentational part of your program from the very beginning of your programming carrier :) You will produce better maintainable programs and you will also see your errors much faster.