我该怎么做才能避免NullPointerException?

时间:2011-08-20 15:10:56

标签: java nullpointerexception client

我正在尝试通过从客户端向服务器发送密钥和随机数来验证用户。

我的代码没有向我显示客户端的响应。当我执行下面的代码时,我得到一个Null Pointer Exception。

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

1 个答案:

答案 0 :(得分:3)

解决大多数NullPointerException s:

的固定步骤
  1. 读取堆栈跟踪以确定抛出NPE的代码行
  2. 在该行代码中设置断点
  3. 使用调试器,当命中断点时,确定该行中的对象引用为null
  4. 弄清楚为什么该引用为null(这是迄今为止唯一的实际难点)
  5. 修复根本原因(也可能很难)
相关问题