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

}}

熱點內容
java返回this 發布:2025-10-20 08:28:16 瀏覽:712
製作腳本網站 發布:2025-10-20 08:17:34 瀏覽:974
python中的init方法 發布:2025-10-20 08:17:33 瀏覽:686
圖案密碼什麼意思 發布:2025-10-20 08:16:56 瀏覽:837
怎麼清理微信視頻緩存 發布:2025-10-20 08:12:37 瀏覽:743
c語言編譯器怎麼看執行過程 發布:2025-10-20 08:00:32 瀏覽:1085
郵箱如何填寫發信伺服器 發布:2025-10-20 07:45:27 瀏覽:314
shell腳本入門案例 發布:2025-10-20 07:44:45 瀏覽:194
怎麼上傳照片瀏覽上傳 發布:2025-10-20 07:44:03 瀏覽:882
python股票數據獲取 發布:2025-10-20 07:39:44 瀏覽:840