[英]Figuring out whether a number is a Double in Java
我是一個Java新手。 我試圖弄清楚一個數字是否是一個像這樣的東西:
if ( typeof ( items.elementAt(1) )== Double ) {
sum.add( i, items.elementAt(1));
}
如果有人能告訴我如何重新排列語法以使其正常工作,我將不勝感激。
試試這個:
if (items.elementAt(1) instanceof Double) {
sum.add( i, items.elementAt(1));
}
反射速度較慢,但適用於您想要知道是狗類型還是貓類而不是動物實例的情況。 所以你要做的事情如下:
if(null != items.elementAt(1) && items.elementAt(1).getClass().toString().equals("Cat"))
{
//do whatever with cat.. not any other instance of animal.. eg. hideClaws();
}
不是說上面的答案不起作用,除了空檢查部分是必要的。
回答這個問題的另一種方法是使用泛型,你可以保證將Double作為任何項目元素。
List<Double> items = new ArrayList<Double>();
由於這是Google提出的第一個問題,我typeof
在此處添加JavaScript樣式類型:
myObject.getClass().getName() // String
使用正則表達式來完成此任務。 請參考以下代碼。
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your content: ");
String data = reader.readLine();
boolean b1 = Pattern.matches("^\\d+$", data);
boolean b2 = Pattern.matches("[0-9a-zA-Z([+-]?\\d*\\.+\\d*)]*", data);
boolean b3 = Pattern.matches("^([+-]?\\d*\\.+\\d*)$", data);
if(b1) {
System.out.println("It is integer.");
} else if(b2) {
System.out.println("It is String. ");
} else if(b3) {
System.out.println("It is Float. ");
}
} catch (IOException ex) {
Logger.getLogger(TypeOF.class.getName()).log(Level.SEVERE, null, ex);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.