【发布时间】:2017-01-11 14:37:59
【问题描述】:
我正在制作一个程序的一部分,该程序将检查输入到 JTextArea 中的字符串是否是数字,如果是,字符串包含什么数字(顺便说一下,不是整个字符串都包含数字,我不不知道这个数字是多少位数)。我已经知道如何从 JTextArea 获取字符串以及如何检查字符串是否包含数字。但我不知道如何从字符串中获取确切的数字。以下是我正在使用的两种方法:
//no problems with this method, it's just here for reference.
public static boolean isNum(char[] c, int index){
//I want to include numbers 0-9
for(int i = 0; i < 10; i++){
if(c[index].equals(i(char)) || c[index].equals('.')){
return true;
}
}
//if the character is not a number 0-9, it is not a number, thus returning false.
return false;
}
和:
//I need a string parameter to make it easier to get the text from the JTextArea
public static float checkNum(String s){
//a List to hold the digits
List<Char> digits = new List<Char>();
//a char array so I can loop through the string
char[] c = s.toCharArray();
for(int i = 0; i < c.length(); i++){
//if the character is not a number, break the loop
if(!isNum(c[i])){
break;
}
else{
//if the character is a number, add it to the next digit
digits.add(c[i]);
}
}
//insert code here.
}
也许我应该将字符列表转换回字符数组,然后将其转换为字符串,然后将其转换为浮点数?如果是这样,我该怎么做?
编辑:谢谢大家,我研究了正则表达式,但我认为这不会完成这项工作。我正在寻找具有未知位数的 一个 号码。不过,我确实知道数字末尾会有一个空格(或至少是一个非数字值)。
【问题讨论】:
-
你能澄清一下吗?使用
BigInteger或BigDecimal可能会解决您的问题,但要澄清一下,您从哪里提取价值?您提到您的整个字符串可能不是一个数字(这很好,因为您可以解析非数字),但只是看到您尝试使用的两种方法,而不是在 what context 他们'用起来有点难。 -
我正在尝试在(各种类型的)等式中查找数字,因此我可以对这些数字进行运算(加、减等)。
标签: java list casting type-conversion