【问题标题】:Java : incompatible types; int cannot be converted to stringJava:不兼容的类型; int 不能转换为字符串
【发布时间】:2020-10-31 13:42:50
【问题描述】:

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

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);在线。

怎么了?

【问题讨论】:

    标签: java types stream


    【解决方案1】:

    DataOutputStream 的方法 writeUTF 需要 String,而您提供了 int

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

    • 继续使用writeUTF(),但随后您必须使用String.valueOf(clients)clients 转换为int
    • 使用writeInt 代替int 而不是String

    总结:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:
        toClient.writeUTF(clients);
        

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

        【讨论】:

          【解决方案4】:

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

          这是签名:

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-12-07
            • 1970-01-01
            • 1970-01-01
            • 2015-12-04
            • 1970-01-01
            • 2014-05-25
            • 2015-04-28
            • 1970-01-01
            相关资源
            最近更新 更多