java 判断一个字符串是否是数字
时间: 2023-09-07 10:17:17 浏览: 50
可以使用 Java 内置的 `Double.parseDouble()` 方法尝试将字符串转换为 double 类型,如果能够成功转换则说明该字符串是数字,否则不是数字。具体代码如下:
```java
public static boolean isNumeric(String str) {
try {
Double.parseDouble(str);
return true;
} catch(NumberFormatException e){
return false;
}
}
```
另外,如果需要判断字符串是否是整数,可以使用正则表达式:
```java
public static boolean isInteger(String str) {
return str.matches("-?\\d+");
}
```
这里的 `-?` 表示可选的负号,`\\d+` 表示一个或多个数字。
相关问题
java判断一个字符串是否全是数字
以下是三种Java判断一个字符串是否全是数字的方法:
1.利用java.lang.Character#isDigit(int)判断所有字符是否为数字字符从而达到判断数字字符串的目的:
```java
public static boolean isNumeric1(String str) {
if (str == null) return false;
for (char c : str.toCharArray ()) {
if (!Character.isDigit(c)) return false;
}
return true;
}
```
2.利用正则表达式判断字符串是否全为数字:
```java
public static boolean isNumeric2(String str){
Pattern pattern = Pattern.compile("[0-9]*");
return pattern.matcher(str).matches();
}
```
3.遍历字符串中的每个字符,判断是否为数字字符:
```java
public static boolean isNumeric3(String str){
for(int i=str.length()-1;i>=0;i--){
int chr=str.charAt(i);
if(chr<48 || chr>57) return false;
}
return true;
}
```
Java判断一个字符串是否全为数字
可以使用Java自带的正则表达式来判断一个字符串是否全为数字:
```
public static boolean isNumeric(String str) {
if (str == null || str.length() == 0) {
return false;
}
return str.matches("\\d+");
}
```
其中,`\d`表示数字,`+`表示匹配一个或多个数字。如果字符串中包含非数字字符,则返回false。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)