简体   繁体   English

此代码是否有可能打印为空?

[英]Is there any chance of this code printing null?

String readwidget(int a, int b){     

    WidgetChild readwidget = Widgets.get(a,b);            
    if(readwidget.getText() != null){         
        Task.sleep(10);
        System.out.println(readwidget.getText());
        return readwidget.getText();
    }

    Task.sleep(10);
    return    GOT_NULL; 

}

while(readFirstWidget.equals(GOT_NULL) && t5.isRunning()) {     

    readFirstWidget = readwidget(1184, 13);
    Task.sleep(50,80);

}

This piece of code is crashing with nullpointerexception once in while(1 out of 50 time) and it prints null at that point of time which it should not. 此段代码在while(50次中的1次)中一次使用nullpointerexception崩溃,并且在该时间点不应打印null。 Can anyone please help me to find out the causes? 谁能帮我找出原因吗? Thanks in advance. 提前致谢。

You mention in a comment that Widgets.get(a,b) can return null . 您在注释中提到Widgets.get(a,b)可以返回null Given that, you need to guard against that possibility by checking the return value from the method for null prior to actually calling any instance methods on it. 鉴于此,您需要通过在实际调用任何实例方法之前检查方法的返回值是否为null来防范这种可能性。 You aren't doing that, and so you are crashing in that case. 您没有这样做,因此在这种情况下会崩溃。

All you need to do is add the null check and your code should be fine: 您需要做的就是添加null检查,您的代码应该可以:

WidgetChild readwidget = Widgets.get(a,b);            
if(readwidget != null && readwidget.getText() != null) { 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM