如何避免NullPointerException? [英] What can I do to avoid a NullPointerException?

查看:198
本文介绍了如何避免NullPointerException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过从客户端向服务器发送密钥和随机数来对用户进行身份验证.

I am trying to authenticate user by sending a key and a random number from the client to the server.

我的代码未向我显示来自客户端的响应.执行下面的代码时,我得到了空指针异常.

My code is not displaying me the response from the client. I am getting a Null Pointer Exception when I execute my code as below.

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的固定步骤:

Canned steps for solving most NullPointerExceptions:

  1. 读取堆栈跟踪以确定哪些代码行引发了NPE
  2. 在该行代码处放置一个断点
  3. 使用调试器,在遇到断点时,确定该行中的哪个对象引用是null
  4. 弄清楚为什么引用是null的原因(这是到目前为止唯一实际的困难部分)
  5. 解决根本原因(也可能很困难)
  1. Read the stack trace to determine what line of code throws the NPE
  2. Put a breakpoint at that line of code
  3. Using the debugger, when the breakpoint is hit, gigure out what object reference in that line is null
  4. Figure out why that reference is null (this is the only actual hard part so far)
  5. Fix the underlying cause (also potentially difficult)

这篇关于如何避免NullPointerException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆