2011-08-20 97 views
0

我想通過從客戶端向服務器發送密鑰和隨機數來驗證用戶身份。我能做些什麼來避免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(); 
    } 
} 
+2

請妥善縮進代碼。這是不可能的。 –

+0

@JB Nizet:ohh對不起,我會做 –

+0

@Parth:「正確縮進」並不意味着所有的東西都有相同的縮進。您的編輯器/ IDE應該有一個縮進代碼的功能,在複製之前使用它。 (我現在爲你做了。) –

回答

3

解決最NullPointerException小號罐頭步驟:

  1. 閱讀堆棧跟蹤,以確定哪些行代碼拋出NPE
  2. 將斷點在該行的代碼
  3. 使用調試器,當命中斷點時,找出該行中的對象引用是null
  4. 找出爲什麼該引用是null(這是迄今爲止唯一實際困難的部分)
  5. 修復的根本原因(也可能存在困難)
+0

通過插入一個斷點並讀取堆棧跟蹤,你的意思是什麼? –

+0

通常,當您在控制檯中看到異常(如「NullPointerException」)時,會看到[堆棧跟蹤](http://en.wikipedia.org/wiki/Stack_trace)已打印出來。這會告訴你異常是由哪一行代碼引發的。至於斷點 - 您是否在使用任何類型的IDE,如Eclipse,NetBeans或IntelliJ?它們都具有集成的調試器,可以用來調試代碼。這裏是一個教程,它解釋瞭如何使用Eclipse的調試器:http://www.vogella.de/articles/EclipseDebugging/article.html –

+0

我寫了我的代碼在記事本中,我用jdk 1.6來運行我的代碼。我猜這是客戶端代碼錯誤「clientout.writeDouble(random)...我猜DataOutputStream應該初始化爲一個值..我對吧? –

相關問題