[英]how to check primitive data type of any value in java
我有一個包含值列表的文件,該值列表可能只是字符串或整數。
bhushan 21
kedar 20
當我讀取字符串數組中的值時,如果我擁有的數據是整數或雙精度數,我也想執行一些算術運算。 如何檢查我擁有的數據是整數,雙精度還是字符串? 我目前正在使用拆分功能將所有值存儲在字符串數組中,每當我想取所有數字的平均值時,我會將我確定的數字轉換為整數或雙精度數,然后執行算術運算。 我想寫一個方法,告訴我該值的類型到底是什么。
使用正則表達式應該是最有效的方法。 其他表達式可用於進一步查找浮點數等。
String input = "12345";
java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(".*[^0-9].*");
if( pattern.matcher(input).matches() )
System.out.println("Its a number");
else
System.out.println("Its not a number");
您也可以使用Integer.parseInt()
或Double.parseDouble()
方法,但是,如果輸入不符合要求,它們將拋出NumberFormatException
。
您可以通過簡單的功能來實現;
public static boolean isValueInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;//For example "bhushan"
}
return true;// For example "21"
}
如果它是一個String
,它將拋出NumberFormatException
您可以嘗試將其從字符串轉換為整數。
try{
int result = Integer.parseInt(stringValue);
} catch (NumberFormatException nfe) {
}
通常,您會使用諸如正則表達式之類的東西。 例如
String number = "daaaa";
Pattern digitPattern = Pattern.compile("\\d{6}");
if (digitPattern.matcher(number).matches()) {
System.out.println(number + " is a number.");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.