我正在制作一个程序的一部分,该程序将检查输入到JTextArea中的字符串是否是数字,如果是,则该字符串包含的数字是方式,而不是整个字符串包含一个数字,我不知道数字是多少位数)。我已经知道如何从JTextArea中获取字符串以及如何检查字符串是否包含数字。但我不知道如何从字符串得到确切的数字。这里有两种方法我一起工作:如何从未知大小的字符串中获取数字(Java)
//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”可能会解决您的问题,但要澄清,您从哪里提取值?你提到你的整个字符串可能不是一个数字(这是很好的,因为你可以解析非数字),但只是看到你正在尝试使用的两种方法,而不是*它们使用的是什么上下文*有点困难。 – Makoto
我试图找到一个方程(各种类型)中的数字,所以我可以用这些数字(加,减等)进行操作。 – MethodHax