开发者

What can I do to avoid a 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(respon开发者_JAVA百科se);    
        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();
    }
}


Canned steps for solving most NullPointerExceptions:

  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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜