简体   繁体   中英

Java, check if int and do something if it is, if it is not int then ignore

How can implement a check in this method to only print out "Message" if it is an integer. But if the message is not integer then don't do anything, just wait for next one, i tried parsing it but if i print out "message" and if "message" is not integer it will print out just empty string.

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();
}

Using Integer.parseInt is one way to tell whether the string is an integer; another simple way is to see if the string consists entirely of digits (with at least one):

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

or, if you need to allow negative numbers,

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

The main difference with this method are that it will allow strings of digits that are too large to fit into an int . This could be a plus or a minus, depending on your needs.

Putting the printing in a try-catch for parsing should do the job. Add this after you declare the message variable:

//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...

That way if the message successfully parses to an int, you do the printing and push the string. If it doesn't you neither print it nor push it. You could do something else instead (in the catch block), but it doesn't seem that you want to.

How about using Regex

\\d ---> Any digit, short for [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");
    }

output:

123456789
-123456789
I am empty sentence

Source: http://www.vogella.com/tutorials/JavaRegularExpressions/article.html

Use can format your code as :

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

}

Can this help?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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