Antoni Dobrenov Antoni Dobrenov - 4 months ago 9
Java Question

Array with 10 elements

I have a one-dimensional array with 10 elements. To find the maximum among the elements with an even index and the minimum from the elements with an odd index:

import java.util.Scanner;

public class Exercise1 {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);
int[] array = new int[10];
System.out.println("Insert elements: ");

for (int i = 0; i < array.length; i++) {

int number = input.nextInt();
array[i] = number;
int max = number;
int min = number;

System.out.println("array[" + i + "] = " + array[i] + " ");

if(i % 2 == 0) {
if(max < number) {
max = number;
}
} else {
if(min>number) {
min = number;
}
}
System.out.println(max + " " + min);
}
}
}


It does not work... Where is my mistake?

Answer

You declared both min and max within your for loop. They will be recreated and initialized for each entered number. Move above your loop and initialize them with min = Integer.MAX_VALUE; max = Integer.Min_VALUE

Comments