簡體   English   中英

服務器端和客戶端,Java

[英]Server and client side, Java

我嘗試使客戶端向服務器發送一些數據。 由於某種原因,它總是進入例外區域...

我只希望服務器接受數據。 之后,它需要執行此簡單功能。

套接字,讀取器和寫入器的初始化可以。

客戶端代碼:

public void SendPlayer(String Name, float Score,int place) throws NullPointerException
{
    out.println("New High Score");
    try
    {
        while (!in.readLine().equals("ACK"));
        out.println(Name);
        out.println(Score);
        out.println(place);
    }
    catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

服務器端代碼:

while(true)
{           
    try
    {
        if (in.ready())
        {
            option = in.readLine();
            while(option == null)
            {
                option = in.readLine();
            }
            switch(option)
            {
                case ("New High Score"):
                {
                    out.println("ACK");
                    System.out.println("ack has been sent");
                    this.setHighScore(in.readLine(),Integer.parseInt(in.readLine()),
                    Integer.parseInt(in.readLine()));
                    break;
                }
                default:
                {
                    System.out.println("nothing");
                    break;
                }
            }
        }
    } 
    catch (Exception e)
    {
        // TODO Auto-generated catch block
        System.out.println("Exception e");
    }
}

您的問題是您無法將null與字符串進行比較。 最好的方法是嘗試捕獲函數調用。

try {
    SendPlayer (/*Here the params*/);
    //Continue, since no null pointer exception has been thrown
} catch (NullPointerException) {
    //Your handling code here...
}

根據您的評論- 完全例外是if(in.ready)行上的NullPointerException

從異常中可以明顯看出,變量in尚未初始化。 請再次檢查。


避免在比較String避免NullPoinerException最佳做法是按相反的順序進行比較,如下所示:

while (!"ACK".equals(in.readLine()));

您的代碼中仍然還有另外一個問題。

客戶端向服務器發送三個值,如下所示:

out.println(Name); // String
out.println(Score);// float
out.println(place); // int

現在在服務器端,您正在使用Integer.parseInt(in.readLine())float轉換為int ,如下所示,這將導致NumberFormatException

this.setHighScore(in.readLine(),Integer.parseInt(in.readLine()),
Integer.parseInt(in.readLine()));// converting Score to int

例如

Integer.parseInt("2.0");

將導致

java.lang.NumberFormatException: For input string: "2.0"

另一個示例代碼

float val = 2;
String str = String.valueOf(val);
Integer.parseInt(str);

將導致

java.lang.NumberFormatException: For input string: "2.0"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM