简体   繁体   中英

Need help in resolving Java String issues

I am developing a programmable calculator in android.I am getting user input in the form of charsequence which i then convert into string. But before i can put them in the stack i must check whether the input is an integer or a sign.

I am basically from a C++ background. So i am having issues finding the right functions to do the job. Any help would be appreciated.

Two possible solutions:

  1. You can create a regex that checks if your string is a number
  2. You can try to extract its integer value using Integer.valueOf() , and catch the exception [ NumberFormatException ] thrown - if it is not a number.

The first is most likely to be more efficient then the second

不允许用户在文本框(Edittext)中输入文本和特殊字符。当用户在文本框中输入数字时,将该数字转换为整数,如下所示Integer.parseInt(yourstring);

You need to us Integer.parseInt and catch the appropriate NumberFormatException if the user does not enter a number:

try
{
  // the String to int conversion happens here
  int i = Integer.parseInt(s.trim());

  // print out the value after the conversion
  System.out.println("int i = " + i);
}
catch (NumberFormatException nfe)
{
  System.out.println("NumberFormatException: " + nfe.getMessage());
}

通过[+ - ]?\\ d *可以匹配此正则表达式的输入验证

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