gpt4 book ai didi

java - split 方法-生成空指针异常

转载 作者:行者123 更新时间:2023-12-01 14:03:02 28 4
gpt4 key购买 nike

我编写了一段代码来计算给定元素列表的因子数。输入:测试 - 测试用例数量num- 1 个测试用例中的元素数量numarr- 字符串,其中的值(要找到其乘积的因子)除以空格。

当输入为:

  • 3
  • 3
  • 3 5 7
  • 3
  • 2 4 6
  • 2
  • 5 5理想情况下,输出应该是
  • 8
  • 10
  • 3

但是,异常(exception)是:

 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;
}
}
}
}

}

最佳答案

想想你的代码在做什么:

if(numarr!=null)
splitt=numarr.split(" ");
if(splitt.length==num)
{
...
}

如果 numarr 为 null,则表示您没有进行拆分,这意味着当您开始使用 splitt 时,它仍然为 null。

将整个内容放入 {} 中。

if(numarr!=null)
{
splitt=numarr.split(" ");
if(splitt.length==num)
{
...
}
}

关于java - split 方法-生成空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19191081/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com