当前位置:首页 » 编程语言 » javastring是数字

javastring是数字

发布时间: 2023-05-21 22:57:45

java中String字符串转化为数字

在java中,要将字符串转换为数字,使用基本数据类型的parseXXX方法,比如:Integer.parseInt()方法转换为整数;Float.parseFloat()方法转换为浮点小数,其它都类似的
举例:
String s = "11";
System.out.println("字符串转换为整数的结果为:" + Integer.parseInt(s));
System.out.println("字符串转换为浮点数的结果为:" + Float.parseFloat(s));
输出结果为:
字符串转换为整数的结果为:11
字符串转换为浮点数的结果为:11.0

② java判断string是不是数字

java中判断字符串是否为数字的方法:

1.用JAVA自带的函数
public static boolean isNumeric(String str){
for (int i = 0; i < str.length(); i++){
System.out.println(str.charAt(i));
if (!Character.isDigit(str.charAt(i))){
return false;
}
}
return true;
}

2.用正则表达式
首先要import java.util.regex.Pattern 和 java.util.regex.Matcher
public boolean isNumeric(String str){
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(str);
if( !isNum.matches() ){
return false;
}
return true;
}

3.使用org.apache.commons.lang
org.apache.commons.lang.StringUtils;
boolean isNunicodeDigits=StringUtils.isNumeric("aaa123456789");
http://jakarta.apache.org/commons/lang/api-release/index.html下面的解释:
isNumeric
public static boolean isNumeric(String str)Checks if the String contains only unicode digits. A decimal point is not a unicode digit and returns false.
null will return false. An empty String ("") will return true.
StringUtils.isNumeric(null) = false
StringUtils.isNumeric("") = true
StringUtils.isNumeric(" ") = false
StringUtils.isNumeric("123") = true
StringUtils.isNumeric("12 3") = false
StringUtils.isNumeric("ab2c") = false
StringUtils.isNumeric("12-3") = false
StringUtils.isNumeric("12.3") = false

Parameters:
str - the String to check, may be null
Returns:
true if only contains digits, and is non-null

上面三种方式中,第二种方式比较灵活。

③ java中,String字符串转化为数字

java中,String字符串转化为数字的方法有:

1、转化为整型数字

(1)Integer.parseInt(String s) ,代码示例如下:

public class Test {

public static void main(String args[]){

String s = "123";

int num = Integer.parseInt(str);

int sum = num + 100;

System.out.println("Result is: "+sum); // 输出结果为:Result is: 223

}}

热点内容
n皇后算法 发布:2025-05-20 01:49:15 浏览:65
如何配置图形电脑 发布:2025-05-20 01:47:51 浏览:391
及解压 发布:2025-05-20 01:44:49 浏览:415
如何用计算器刷安卓 发布:2025-05-20 01:09:29 浏览:576
移动宽带密码重置后怎么办 发布:2025-05-20 01:02:04 浏览:808
php不是内部命令 发布:2025-05-20 00:41:09 浏览:97
淘宝图片上传用什么软件 发布:2025-05-20 00:40:55 浏览:346
mysql64位forlinux 发布:2025-05-20 00:37:25 浏览:345
工伤辅助器如何配置 发布:2025-05-20 00:25:13 浏览:602
opencv存储图片 发布:2025-05-20 00:16:10 浏览:953