gpt4 book ai didi

java - 如何处理空指针异常?

转载 作者:行者123 更新时间:2023-12-01 23:30:55 27 4
gpt4 key购买 nike

我的 java 类中有下面的代码。

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package webservice;

import java.util.Iterator;
import java.util.List;


public class Webservice {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
ArrayOfString aar = new ArrayOfString();
aar.getString().add("1025976002");
aar.getString().add("1026020904");
aar.getString().add("1026020704");
aar.getString().add("1026026201");
aar.getString().add("1026036901");
aar.getString().add("");
ArrayOfStatusContainer status = getStatusList(aar);
List<StatusContainer> li = status.getStatusContainer();
Iterator litr=li.listIterator();
// System.out.println("Elements in forward directiton");
while(litr.hasNext()){
StatusContainer test = (StatusContainer)litr.next();
System.out.println(test.getStatus());
}

}

private static ArrayOfStatusContainer getStatusList(webservice.ArrayOfString keys) {
webservice.AdStatusWS service = new webservice.AdStatusWS();
webservice.AdStatusWSSoap port = service.getAdStatusWSSoap();
return port.getStatusList(keys);

}
}

每当我输入空字符串或输入重复的字符串值时,我都会收到空指针异常。我已经尝试了一段时间,但到目前为止我还没有找到解决方案。我附上了下面的异常的屏幕截图。堆栈跟踪如下:

Sent
Booked
Multiple Errors
Exception in thread "main" java.lang.NullPointerException
In QC
Need correction client
at webservice.Webservice.main(Webservice.java:34)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)

enter image description here

最佳答案

控制台说第 34 行抛出了空指针异常,这可能意味着测试变量为空,并且您正在尝试访问对象的属性 null 首先验证 null。

 while(litr.hasNext()){  
StatusContainer test = (StatusContainer)litr.next();
if(test != null)
System.out.println(test.getStatus());
}

关于java - 如何处理空指针异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19321431/

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