[英]How to check if a string contains a numerical value
I want to know how to do I check my sub string if it is a numerical value or if it is just words.我想知道如何检查我的子字符串是数值还是只是单词。
For example, if my substring d=150.63例如,如果我的子串 d=150.63
I have done some research and I've found Character.is Digit()
, but it is not working.我做了一些研究,发现Character.is Digit()
,但它不起作用。 Below is the code I have made so far.下面是我到目前为止所做的代码。
import java.util.*;
import java.io.*;
public class Prac34 {
private Scanner x;
public void openFile(){
try{
x=new Scanner(new File("sales.txt"));
}
catch (Exception e){
System.out.println("could not find file");
}
}
public void readFile(){
//int count=0;
double total=0;
while(x.hasNext()){
String a=x.nextLine();
int v=a.length();
int b=a.indexOf(':');
String c= a.substring(0,(b+1));
String d=a.substring((b+1),v);
double e= Double.parseDouble(d);
if (Character.isDigit(d)) {
total=total+e;
}
System.out.println(c);
System.out.println(d);
}
}
public void closeFile(){
x.close();
}
}
You could just try to parse the string:您可以尝试解析字符串:
try {
double e = Double.parseDouble(d);
total += e;
} catch (NumberFormatException ignore) {
// Not a number, skipping
}
Using a regex (regular expression):使用正则表达式(正则表达式):
String text="25.54";
if(text.replace(".","").matches("[0-9]+")){ //or you can use also "\\d+"
System.out.println("digit");
}else{
System.out.println("no digit");
}
System.out.println(text);
Also:还:
where ( ? ) means none or one time其中 ( ? ) 表示没有或一次
where (*) means none or more times其中 (*) 表示没有或多次
where ( + ) means one or more times其中 ( + ) 表示一次或多次
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.