Reputation: 764
Java newbie here. I have the following code from which I would want it to return the middle elements of the array. How do I go about that? I don't want to just manually return the elements at position 5 and 6, which are the median elements here. I would it in a way that would work for any array type, even or odd.
/**
* 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");
}
}
}
Upvotes: 1
Views: 12193
Reputation: 71
Here is another solution step by step. It is less elegant of course, but tailored for beginners. It uses the modulus operator to check for even or odd lengths, adjusts for using zero indexed arrays, then makes a decision based on the outcome.
In main() declare a String and initialize it with a call to this method, with your names array passed in as a parameter. Then in the next line, print the String.
public String returnMiddleElement( String[] input ){
/* Initialize result variable */
String result = "";
/* Determine if the array is odd or even */
int value = input.length % 2;
/* Obtain the middle index */
int middleIndex = input.length/2;
/* Adjust for the zero index of arrays */
int evenMid = middleIndex - 1;
if( value == 0 ){
/* The array is even, so obtain the two middle elements */
result += input[evenMid] + "\n" + input[(evenMid+1)];
}
else{
/* The array is odd, so obtain the single middle element */
result += input[middleIndex];
}
return result;
}
Upvotes: 1
Reputation: 3785
Write a method like :
void printMiddleofArray(String[] arrayOfNames) {
if (arrayOfNames.length %2 ==0)
{
System.out.println(arrayOfNames[arrayOfNames.length /2]);
System.out.println(arrayOfNames[(arrayOfNames.length /2)-1]);
} else {
System.out.println(arrayOfNames[(arrayOfNames.length /2)-1]);
}
}
Upvotes: 2