我编写了一个代码来计算给定元素列表的因子数。INPUT: test- 测试用例数 num- 1 个测试用例中的元素数 numarr- 其中值(要找到其乘积的因子)除以空格的字符串。
当输入为:
- 3
- 3
- 3 5 7
- 3
- 2 4 6
- 2
- 5 5 理想情况下,输出应该是
- 8
- 10
- 3
但是,例外是:
Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:31)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int test = 0;
Scanner scn = new Scanner(System.in);
if (scn.hasNextLine())
test = scn.nextInt();
int op = 0;
int[] out = new int[test];
while ((test <= 100) && (test > 0)) {
int num = 0;
if (scn.hasNextLine())
num = scn.nextInt();
if (num <= 10) {
String numarr = null;
Scanner sc = new Scanner(System.in);
if (sc.hasNextLine())
numarr = sc.nextLine();
String splitt[] = null;
if (numarr != null)
splitt = numarr.split(" "); <--ERROR!!!
if (splitt.length == num) {
double[] arr = new double[splitt.length];
int i = 0;
while (i < splitt.length) {
arr[i] = Double.parseDouble(splitt[i]);
++i;
}
i = 0;
double prod = 1;
while (i < arr.length) {
prod *= arr[i];
++i;
}
double[] factor = new double[100000];
int value = 0;
pfac(prod, factor);
for (i = 0; (i < factor.length) && (factor[i] != 0); ++i) {
value += 1;
}
out[op] = value;
op++;
}
}
--test;
}
for (int i = 0; i < op; ++i) {
System.out.println(out[i]);
}
}
private static void pfac(double n, double[] factor) {
int pos = 0;
long max = (long) Math.sqrt(n);
for (long i = 1; i <= max; ++i) {
if (n % i == 0) {
factor[pos] = i;
pos += 1;
if (n / i != i) {
factor[pos] = n / i;
pos += 1;
}
}
}
}
}