2016-09-03 45 views
1

我正在制作一个程序的一部分,该程序将检查输入到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. 
} 

也许我应该焦炭列表转换回一个字符数组,然后将其转换为字符串,然后将其转换为浮动?如果是这样,我该怎么做?

编辑:谢谢你们,我看着正则表达式,但我不认为会做这项工作。我在寻找其中一个数字未知的数字。不过,我知道这个号码最后会有一个空格(或者至少是一个非数字值)。

+0

你能否澄清一点?使用“BigInteger”或“BigDecimal”可能会解决您的问题,但要澄清,您从哪里提取值?你提到你的整个字符串可能不是一个数字(这是很好的,因为你可以解析非数字),但只是看到你正在尝试使用的两种方法,而不是*它们使用的是什么上下文*有点困难。 – Makoto

+0

我试图找到一个方程(各种类型)中的数字,所以我可以用这些数字(加,减等)进行操作。 – MethodHax

回答

3

您应该使用正则表达式。在Java中,你可以通过这样的数字每一个实例循环:

java.util.regex.Pattern; 
java.util.regex.Matcher; 

Pattern p = Pattern.compile("\\d+?\\.\\d+"); 
Matcher m = p.matcher(inputString); 

while(m.find()) 
    //do some string stuff 

或者你可以用这个代替while循环寻找一个匹配一组数字组成的字符串中:

String digits = m.group(1); 
double number = Double.valueOf(digits); 

有关这种工作方式的更多信息,请查看正则表达式。此网站特别有帮助https://regexone.com/

+0

您使用匹配的示例不正确。 'String.matches(String expr)'返回'boolean'' – pczeus

+0

另外,'String.numericValueOf'不存在。 –

+0

谢谢,这似乎会工作,如果我修改它,以适应我在做什么。但我不会知道一点,因为我现在没有什么东西来测试代码。 – MethodHax

0

您可以使用正则表达式来测试和提取任意长度的数字。 下面是一个例子简单的方法是做到了这一点:

public Integer extractNumber(String fromString){ 
    Matcher matcher = Pattern.compile("\\D*(\\d+)\\D*").matcher(fromString); 
    return (matcher.matches()) ? new Integer(matcher.group(1)) : null; 
} 

如果要数内处理小数,您可以更改方法:

public Double extractNumber(String fromString){ 
    Matcher matcher = Pattern.compile("\\D*(\\d+\\.?\\d+)\\D*").matcher(fromString); 
    return (matcher.matches()) ? new Double(matcher.group(1)) : null; 
} 
相关问题