2017-04-20 109 views
-2

這是程序找到任何數字的最大prme因數。爲什麼我在程序中得到java.lang.NullPointerException?我沒有看到任何錯誤

// Program to get the largest prime factor of a number 

import java.util.*; 

class factor{ 

    ArrayList<Long> a; 

    public void large(long n){ 
     for(long i = 1; i <= n; i++){ 
      if (n % i == 0){ 
       a.add(i); 
      } 
     } 
     System.out.println(Collections.max(a)); 
    } 
} 

class test{ 
    public static void main(String[] args){ 
     factor g = new factor(); 
     g.large(13195); 
    } 
} 
+4

您還沒有初始化'a'。這是顯而易見的。不是你甚至需要它。沒有它,該方案會更好。 – EJP

+1

ArrayList a永遠不會初始化 – matcheek

回答

0

你需要初始化你的列表,然後調用它的任何方法。

class Factor{ 

    List<Long> a = new ArrayList<>(); 

    public void large(long n){ 
     for(long i = 1; i <= n; i++){ 
      if (n % i == 0){ 
       a.add(i); 
      } 
     } 
     System.out.println(Collections.max(a)); 
    } 
} 
相關問題