简体   繁体   English

如何检查来自客户端的输入流是否为int数据?

[英]How do I check if the inputstream from client side is an int data?

In my client-server program, the client should be able to send string and int value. 在我的客户端服务器程序中,客户端应该能够发送stringint值。 The server will accept and do corresponding operation only when it is a string . 服务器只有在为string时才接受并执行相应的操作。 Otherwise, if its an int , the server shouln't be able to handle it (or do nothing with it). 否则,如果它是一个int ,则服务器将无法处理它(或对其不执行任何操作)。 How do I implement this logic inside an if statement. 如何在if语句中实现此逻辑。 I was trying with something like this, but hasNextInt() method shows error: 我正在尝试类似的事情,但是hasNextInt()方法显示错误:

if(!incomingInput.hasNextInt){
//do nothing
}

This is the part where I am working in: 这是我正在工作的部分:

   if (msgFromClient != null && !msgFromClient.hasNextInt()) {
                    OutputStream clientOut = client.getOutputStream();
                    PrintWriter pw = new PrintWriter(clientOut, true);
                    String ansMsg = "Hello, " + msgFromClient;
                    pw.println(ansMsg);

                }

Based on the code you've posted, it looks like you're just taking the value from the stream and parsing it as a string. 根据您发布的代码,您似乎只是从流中获取值并将其解析为字符串。 If you take it as a string, you could call 如果将其作为字符串,则可以调用

Integer.parseInt(ansMsg);

Which will throw a NumberFormatException if the value is not an integer. 如果该值不是整数,则将引发NumberFormatException。 At this point you can handle the exception as you like (by doing nothing). 此时,您可以根据需要处理异常(不执行任何操作)。 You'd need to use a try catch statement, but that's one way to go about it. 您需要使用try catch语句,但这是解决问题的一种方法。

   try{
      int num = Integer.parseInt(str);
      //if int
    } catch (NumberFormatException e) {

      return; //Do nothing.
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM