2017-04-20 72 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)); 
    } 
} 
相关问题