2017-02-22 670 views
1
public class tryA { 

    public static void main(String[] args) { 
    int[] intArray= new int[41]; 
    System.out.println(intArray[intArray.length/2]); 

} 

如何为我的整型数组intArray找到下四分位数(Q1)和第三四分位数(Q3)?假设数组的大小可能是一个变量。使用java查找整数数组中的第一四分位数和第三四分数

P.S:它用于查找数组的异常值。

+0

你想使用哪种方法?你需要告诉我们这一点。 –

+0

我试着用double LQ =(intArray [(median + 1)/ 2] + intArray [(median-1)/ 2])/2.0找到第一个四分位数;但似乎并不总是有效的 –

回答

0

我相信这是你正在寻找的,在代码顶部更改quartile变量以在Q1,Q2,Q3和Q4之间切换。

import java.util.Arrays; 

public class ArrayTest 
{ 
    public static void main(String[] args) 
    { 
     //Specify quartile here (1, 2, 3 or 4 for 25%, 50%, 75% or 100% respectively). 
     int quartile = 1; 

     //Specify initial array size. 
     int initArraySize = 41; 

     //Create the initial array, populate it and print its contents. 
     int[] initArray = new int[initArraySize]; 
     System.out.println("initArray.length: " + initArray.length); 
     for (int i=0; i<initArray.length; i++) 
     { 
      initArray[i] = i; 
      System.out.println("initArray[" + i + "]: " + initArray[i]); 
     } 

     System.out.println("----------"); 

     //Check if the quartile specified is valid (1, 2, 3 or 4). 
     if (quartile >= 1 && quartile <= 4) 
     { 
      //Call the method to get the new array based on the quartile specified. 
      int[] newArray = getNewArray(initArray, quartile); 
      //Print the contents of the new array. 
      System.out.println("newArray.length: " + newArray.length); 
      for (int i=0; i<newArray.length; i++) 
      { 
       System.out.println("newArray[" + i + "]: " + newArray[i]); 
      } 
     } 
     else 
     { 
      System.out.println("Quartile specified not valid."); 
     } 
    } 

    public static int[] getNewArray(int[] array, float quartileType) 
    { 
     //Calculate the size of the new array based on the quartile specified. 
     int newArraySize = (int)((array.length)*(quartileType*25/100)); 
     //Copy only the number of rows that will fit the new array. 
     int[] newArray = Arrays.copyOf(array, newArraySize); 
     return newArray; 
    } 
} 
相关问题