Java Method to Find Middle Element of String Array
public class MiddleElementFinder { public static String findMiddleElement(String[] array){ if (array.length % 2 == 0) { return 'Array length is even. No middle element exists'; } else { return array[array.length / 2]; } }
public static void main(String[] args) {
String[] array1 = {'apple', 'banana', 'cherry', 'date', 'elderberry'};
String[] array2 = {'alpha', 'bravo', 'charlie', 'delta', 'echo', 'foxtrot'};
System.out.println('Middle element of array1: ' + findMiddleElement(array1));
System.out.println('Middle element of array2: ' + findMiddleElement(array2));
}
}
//Output: //Middle element of array1: cherry //Middle element of array2: Array length is even. No middle element exists
原文地址: https://www.cveoy.top/t/topic/lPz6 著作权归作者所有。请勿转载和采集!