我能做些什么来避免NullPointerException?
我想通过从客户端向服务器发送密钥和随机数来验证用户身份。我能做些什么来避免NullPointerException?
我的代码没有显示客户端的响应。当我执行我的代码时,我得到一个空指针异常。
import java.io.*;
import java.net.*;
import java.lang.*;
class Client
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the key value");
int key=Integer.parseInt(br.readLine());
double random=Math.random()*50;
System.out.println(random);
int response=key%((int)random);
System.out.println(key);
System.out.println("Authentication begins");
Socket echoSocket = new Socket("localhost", 2000);
FileOutputStream fout=null;
DataOutputStream clientout=null;
clientout.writeDouble(random);
clientout.writeInt(key);
clientout.writeInt(response);
fout.flush();
System.out.println("client is"+response);
echoSocket.close();
}
}
import java.io.*;
import java.net.*;
import java.lang.*;
class Server
{
public static void main(String args[]) throws IOException
{
int response2;
double random2;
int key2;
FileInputStream fin=null;
DataInputStream clientin=null;
ServerSocket s= new ServerSocket(2000);
Socket echoSocket=s.accept();
random2=clientin.readDouble();
key2=clientin.readInt();
response2=clientin.readInt();
response2=key2%((int)random2);
System.out.println("server is"+response2);
s.close();
echoSocket.close();
}
}
解决最NullPointerException
小号罐头步骤:
- 阅读堆栈跟踪,以确定哪些行代码抛出NPE
- 将断点在该行的代码
- 使用调试器,当命中断点时,找出该行中的对象引用是
null
- 找出为什么该引用是
null
(这是迄今为止唯一实际困难的部分) - 修复的根本原因(也可能存在困难)
通过插入一个断点并读取堆栈跟踪,你的意思是什么? –
通常,当您在控制台中看到异常(如“NullPointerException”)时,会看到[堆栈跟踪](http://en.wikipedia.org/wiki/Stack_trace)已打印出来。这会告诉你异常是由哪一行代码引发的。至于断点 - 您是否在使用任何类型的IDE,如Eclipse,NetBeans或IntelliJ?它们都具有集成的调试器,可以用来调试代码。这里是一个教程,它解释了如何使用Eclipse的调试器:http://www.vogella.de/articles/EclipseDebugging/article.html –
我写了我的代码在记事本中,我用jdk 1.6来运行我的代码。我猜这是客户端代码错误“clientout.writeDouble(random)...我猜DataOutputStream应该初始化为一个值..我对吧? –
请妥善缩进代码。这是不可能的。 –
@JB Nizet:ohh对不起,我会做 –
@Parth:“正确缩进”并不意味着所有的东西都有相同的缩进。您的编辑器/ IDE应该有一个缩进代码的功能,在复制之前使用它。 (我现在为你做了。) –