Java新手在這裏。 我有下面的代碼,我希望它返回數組的中間元素。我該如何解決這個問題?我不想僅僅手動返回位置5和6的元素,這裏是元素的中位數。我會以一種適用於任何數組類型的方式,即使或奇數。查找數組的中間元素
/**
* Created by root on 2/11/15.
*/
import java.util.Scanner;
import java.util.Arrays;
public class test {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
//Create a string array to store the names
String arrayOfNames[] = new String[10];
System.out.print("Enter 10 names\n");
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("\n" + (i+1) + " : ");
arrayOfNames[i] = scan.nextLine();
}
//show name one by one
Arrays.sort(arrayOfNames);
System.out.print("Names ");
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("" + (i+1) + " : ");
System.out.print(arrayOfNames[i] + "\n");
}
}
}
@維諾德......正如他所說的應該是5和6 – Rehman
應爲5和6,雖然只是通過把arrayOfNames在指數5 – pycod333