Java:不兼容的类型; int无法转换为字符串

时间:2020-10-31 13:42:50

标签: java types stream

我只是想通过套接字从服务器向客户端发送一个整数。

public static DataOutputStream toClient = null;
public static int clients = 0;

public static void main(String args[]) throws IOException {

        ServerSocket serverSocket = new ServerSocket(1039);
        System.out.println("Server is running..");

        while (true) {
            Socket connsock = null;
            try {
                // accepting client socket
                connsock = serverSocket.accept();

                toClient = new DataOutputStream(connsock.getOutputStream());
                
                System.out.println("A new client is connected : " + connsock);

                clients = clients + 1;
                toClient.writeUTF(clients); //here, I get the incompatible types; int cannot be converted to string
            }
        }
    }
}

我得到:

不兼容的类型; int无法转换为字符串

toClient.writeUTF(clients);一行。

怎么了?

4 个答案:

答案 0 :(得分:2)

在您提供writeUTF时,DataOutputStream的方法String期望有int

当您要发送int时,我会考虑以下两个选项:

  • 继续使用writeUTF(),但是您必须使用clientsint转换为String.valueOf(clients)
  • 使用writeInt而不是int发送普通的String

摘要:

// convert to String
toClient.writeUTF(String.valueOf(clients));
// send a single plain int value
toClient.writeInt(clients);

答案 1 :(得分:1)

这是因为DataOutputStream中的writeUTF没有接受int的重载方法。因此,您需要将int转换为String:Integer.toString(i)

答案 2 :(得分:0)

writeUTF方法使用字符串参数,但是代码中的clients变量是整数类型。

这是签名:

public final void writeUTF(String str) throws IOException {
    writeUTF(str, this);
}

答案 3 :(得分:0)

toClient.writeUTF(clients);

在这里writeUTF(String str)具有字符串类型参数,因此您必须将客户端整数更改为字符串类型。