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

Java Method to Find Middle Element of String Array

原文地址: https://www.cveoy.top/t/topic/lPz6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录