Java 只是字符串中的数字
我有随机生成的字符串(例如Java 只是字符串中的数字,java,string,double,Java,String,Double,我有随机生成的字符串(例如138fj*28+/dg) 如何测试给定字符串是否仅由数字组成。比如说, if(str="247339") true; else if(str="a245") false; 尝试使用Pattern类的matches方法 boolean b = Pattern.matches("\\d+", "138fj*28+/dg"); if(b) //number else // not a number 您可以在字符串中使用matches方
138fj*28+/dg
)
如何测试给定字符串是否仅由数字组成。比如说,
if(str="247339")
true;
else if(str="a245")
false;
尝试使用Pattern类的matches方法
boolean b = Pattern.matches("\\d+", "138fj*28+/dg");
if(b)
//number
else
// not a number
您可以在字符串中使用matches方法。 e、 g 输出:
Only integer 23343453 :true
With character 2334a3453 :false
With symbols 2*33434/53 :false
Only integer 23343453 :true
With character 2334a3453 :false
With symbols 2*33434/53 :false
您有两个选项,一个是使用正则表达式,另一个是解析字符串 以下是正则表达式方法:
public class Main {
public static void main(String[]args) {
Pattern pattern = Pattern.compile("^[0-9]*$");
Matcher matcher = pattern.matcher("138fj*28+/dg");
if (matcher.matches()) {
System.out.println(true);
// number
}else {
System.out.println(false);
// not
}
}
}
输出为:false
以下是解析方法:
public class Main {
public static void main(String[]args) {
try {
double number = Double.parseDouble("138fj*28+/dg");
System.out.println(true);
// number
}catch (NumberFormatException ex) {
System.out.println(false);
// not
}
}
}
输出为:false查看正则表达式模式和匹配器
public class Main {
public static void main(String[]args) {
try {
double number = Double.parseDouble("138fj*28+/dg");
System.out.println(true);
// number
}catch (NumberFormatException ex) {
System.out.println(false);
// not
}
}
}