问题描述
例:classA{PrintWriterout=null;privatevoidf(){Sockets=newSocket(ip,port);out=newPrintWriter(s.getOutputStream(),true);}publicvoids(Stringstr){out.println(str);}}【问题】函数s中调用out会有空指针异常,怎么解决?Exceptioninthread"AWT-EventQueue-0"java.lang.NullPointerExceptionatnetwork.Connect.sendMsg(Connect.java:101)//改行是s方法下的out.println(str;)atFram.Login$1.mouseClicked(Login.java:43)//该行是调用s方法atjava.awt.AWTEventMulticaster.mouseClicked(UnknownSource)atjava.awt.Component.processMouseEvent(UnknownSource)atjavax.swing.JComponent.processMouseEvent(UnknownSource)atjava.awt.Component.processEvent(UnknownSource)atjava.awt.Container.processEvent(UnknownSource)atjava.awt.Component.dispatchEventImpl(UnknownSource)atjava.awt.Container.dispatchEventImpl(UnknownSource)atjava.awt.Component.dispatchEvent(UnknownSource)atjava.awt.LightweightDispatcher.retargetMouseEvent(UnknownSource)atjava.awt.LightweightDispatcher.processMouseEvent(UnknownSource)atjava.awt.LightweightDispatcher.dispatchEvent(UnknownSource)atjava.awt.Container.dispatchEventImpl(UnknownSource)atjava.awt.Window.dispatchEventImpl(UnknownSource)atjava.awt.Component.dispatchEvent(UnknownSource)atjava.awt.EventQueue.dispatchEventImpl(UnknownSource)atjava.awt.EventQueue.access$200(UnknownSource)atjava.awt.EventQueue$3.run(UnknownSource)atjava.awt.EventQueue$3.run(UnknownSource)atjava.security.AccessController.doPrivileged(NativeMethod)atjava.security.ProtectionDomain$1.doIntersectionPrivilege(UnknownSource)atjava.security.ProtectionDomain$1.doIntersectionPrivilege(UnknownSource)atjava.awt.EventQueue$4.run(UnknownSource)atjava.awt.EventQueue$4.run(UnknownSource)atjava.security.AccessController.doPrivileged(NativeMethod)atjava.security.ProtectionDomain$1.doIntersectionPrivilege(UnknownSource)atjava.awt.EventQueue.dispatchEvent(UnknownSource)atjava.awt.EventDispatchThread.pumpOneEventForFilters(UnknownSource)atjava.awt.EventDispatchThread.pumpEventsForFilter(UnknownSource)atjava.awt.EventDispatchThread.pumpEventsForHierarchy(UnknownSource)atjava.awt.EventDispatchThread.pumpEvents(UnknownSource)atjava.awt.EventDispatchThread.pumpEvents(UnknownSource)atjava.awt.EventDispatchThread.run(UnknownSource)注解:使用时,外部类调用方法s,通过socket向服务器发送数据
解决方案
解决方案二:
解决方案三:
你要保证out已经被初始化童鞋
解决方案四:
代码中,没看到out未赋值,应该指向了一个null。。。。。。当然报空指针异常了