當前位置:首頁 » 編程語言 » 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

}}

熱點內容
如何用計算器刷安卓 發布: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
ug編程鏈輪 發布:2025-05-20 00:14:03 瀏覽:100
手機鎖屏壁紙配置失敗怎麼解決 發布:2025-05-20 00:10:38 瀏覽:757
源碼編譯的軟體怎麼卸載 發布:2025-05-20 00:05:29 瀏覽:489