2016-02-29 23 views
0

所以我有一個項目需要擴展Number的泛型類,並且還可以找到數組中的最大值和最小值,所有值的平均值以及數組的大小。這似乎很容易實現,但即使將通用部分放在適當位置之前,我也遇到了一個問題,無論我調用哪種方法,總是在相同的位置,我在x.length處得到空指針異常的運行時錯誤。數組傳遞類中的空指針異常

import java.util.Comparator; 

public class test 
{ 
    public int x[]; 

    public test(int x[]) 
    { 

    } 

    public void setx(int newx[]) 
    { 
    x = newx; 
    } 

    public int[] getx() 
    { 
    return x; 
    } 



public int findSmallest() 
{ 
    int i = 0; 
    int temp = x[i]; 

    while (i < x.length) 
    { 
     i++; 
     if(x[i] < temp) 
     { 
     temp = x[i];  
     } 
     else 
     { 

     } 

    } 

    return temp; 

    } 



public int findLargest() 
{ 
    int i = 0; 
    int temp = x[i]; 


    while (i < x.length) 
    { 
     i++; 
     if(x[i] > temp) 
     { 
     temp = x[i]; 
     } 
     else 
     { 

     } 

    } 

    return temp; 

    } 

public double findMean() 
{ 
    int i = 0; 
    double sum = 0.0; 
    double avg = 0.0; 

    while (i < x.length) 
    { 
     sum += x[i]; 
     i++; 
    } 

    avg = sum/x.length; 
    return avg; 
} 

public int findTotal() 
{ 

    int i = x.length; 

    return i; 

} 

public static void main (String args[]) 
{ 

int[] ia = {1, 2, 3, 4, 5, 6}; 

test intTest = new test(ia); 

System.out.println(intTest.findTotal()); 

} 


} 



Any help on how to fix this would be amazing. 

回答

0

你忘了在構造函數中使用setx方法。您將整數數組傳遞給構造函數,但實際上並未初始化類中的整數數組。您可以通過在構造函數中調用setx方法並將整數數組x傳遞給setx方法來完成此操作。 希望這有助於。