当前位置: 首页 > 知识库问答 >
问题:

Java:不兼容类型;int不能转换为字符串

汝吕恭
2023-03-14
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
            }
        }
    }
}

在带有Toclient.WriteUtf(客户端);的行上。

怎么啦?

共有1个答案

东方和志
2023-03-14

DataOutputStream的WriteUTF方法需要一个String,而您提供了一个Int

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

  • 继续使用writeutf(),但您必须使用字符串将clients转换为int
  • 改用writeint发送纯int而不是字符串

摘要:

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

 类似资料: