我该怎么做才能避免

我该怎么做才能避免

本文介绍了我该怎么做才能避免 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();
    }
}

推荐答案

解决大多数NullPointerExceptions的固定步骤:

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 15:03