【问题标题】:Java, check if int and do something if it is, if it is not int then ignoreJava,检查是否为int,如果是则做某事,如果不是int则忽略
【发布时间】:2014-09-16 15:05:57
【问题描述】:

如何在此方法中实现检查以仅在“消息”为整数时打印出来。 但是如果消息不是整数,那么什么都不做,等待下一个,我尝试解析它,但是如果我打印出“消息”并且如果“消息”不是整数,它将只打印出空字符串。

void startListenForTCP (String ipaddress){




Thread TCPListenerThread;
   TCPListenerThread = new Thread(new Runnable() {
       @Override

       public void run() {

           Boolean run = true;
           String serverMessage = null;
           InetAddress serverAddr = null;


           try {

               Socket clientSocket = new Socket(ipaddress, 7420);

               try
               {
                   mc.pushNumbers("Connection initiated... waiting for outputs!"+"\n");
                   char[] buffer = new char[2048];
                   int charsRead = 0;  
                   BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                   while ((charsRead = in.read(buffer)) != -1)
                   {


                        String message = new String(buffer, 0, charsRead);

                       String m = message;

                       //I need to print out 'm' if it an numberhere

                       System.out.println("Result:"+m);
                       mc.pushNumbers(m);


                   }}
               catch(UnknownHostException e) {

                   mc.pushNumbers("Unknown host..."+"\n");
               } catch(IOException e) {
                   mc.pushNumbers("IO Error..."+"\n");
               } finally {
                   clientSocket.close();
               }

           } catch (IOException e) {
               e.printStackTrace();
                 mc.pushNumbers("Connection refused by machine..."+"\n");
           }
       }

   });
TCPListenerThread.start();
}

【问题讨论】:

  • 您能指出您在代码中解析过的那一行或多行吗?
  • 不,不,我已经尝试解析它并且没有解析,我将立即在底部添加解析部分。
  • 很不清楚您在问什么或在说什么?你能澄清一下吗?
  • 好的,我从缓冲阅读器得到字符串'm',那个字符串可以是任何东西。但我想打印出接收到的字符串是否为 int,如果不是 int,则忽略该字符串继续阅读。

标签: java


【解决方案1】:

使用Integer.parseInt 是判断字符串是否为整数的一种方法;另一种简单的方法是查看字符串是否完全由数字组成(至少有一个):

if (m.matches("\\d+")) {
    mc.pushNumbers(m);
}

或者,如果您需要允许负数,

if (m.matches("-?\\d+")) {
    mc.pushNumbers(m);
}

此方法的主要区别在于它允许数字字符串太大而无法放入int。根据您的需要,这可能是一个加号或减号。

【讨论】:

    【解决方案2】:

    将打印放在 try-catch 中进行解析应该可以完成这项工作。在声明消息变量后添加:

    //Rest of your code...
    
    String message = new String(buffer, 0, charsRead);
    try{
        int i = Integer.parseInt(message);
        System.out.println(i);
        mc.pushNumbers(message);
    } catch(NumberFormatException e){
        //Input was not a number... Do nothing else
    }
    
    //Rest of your code...
    

    这样,如果消息成功解析为 int,您就可以打印并推送字符串。如果不是,您既不打印也不推送。您可以改为执行其他操作(在 catch 块中),但您似乎不想这样做。

    【讨论】:

      【解决方案3】:

      如何使用正则表达式

      \d ---> 任意数字,[0-9]的缩写

         String regex = "[0-9]+|-\\d+"; <---- **Accepting positive and negative number** 
      
          // Accepting negative number
          String number= "-123456789";
          if (data.matches(regex)) {
              System.out.println(number);
          } else {
              System.out.println(" I am empty sentence");
          }
          // Accepting Positive number
          String number= "123456789";
          if (data.matches(regex)) {
              System.out.println(number);
          } else {
              System.out.println(" I am empty sentence");
          }
      
          String string = "I am a String";
          if (string.matches(regex)) {
              System.out.println(string);
          } else {
              System.out.println("I am empty sentence");
          }
      

      输出:

      123456789
      -123456789
      I am empty sentence
      

      来源:http://www.vogella.com/tutorials/JavaRegularExpressions/article.html

      【讨论】:

        【解决方案4】:

        这有帮助吗?

         if(Character.isDigit(evt.getKeyChar())){
           // put something here
        
         }
         else if(!(Character.isDigit(evt.getKeyChar())){
           //.......     
            }
        

        【讨论】:

        • 这是很奇怪的代码。大概isDigit 返回一个布尔值,所以你不需要else if 只是一个else
        【解决方案5】:

        使用可以将您的代码格式化为:

        try {
          int i = Integer.parseInt(yourString);
          mc.pushNUmber(i);
        } catch (NumberFormatException e){
        
        }
        

        【讨论】:

        • 线程“Thread-2”中的异常 java.lang.RuntimeException: 无法编译的源代码 - 类型的非法开始 这是我得到的错误。
        • @wumm 但是一旦我修复了 catch 块呢?我虽然很明显 OP 会理解...
        • @Aeshang 我不能告诉你。我刚看到这个帖子,因为您似乎不知道有关您帖子的讨论,所以我发布了链接。
        猜你喜欢
        • 2011-02-26
        • 1970-01-01
        • 1970-01-01
        • 2015-05-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-18
        • 2011-12-13
        相关资源
        最近更新 更多