Re: [問題] Object陣列轉int

看板java作者 (真肉)時間11年前 (2013/10/09 22:43), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/2 (看更多)
※ 引述《gewabavv (昂流)》之銘言: : Object o[]={new Integer(1), new Double(1.2), new Float(1.6), new String("app")} : 想請教一個問題,一個物件陣列如上所示,如何把陣列的元素全部轉成int, : 這是我目前想到的方法 : int a0=Integer.parseInt(o[0].toString()); : double a1=(Double) o[1]; : int a11=(int) a1; : float a2=(Float) o[2]; : int a22=(int) a2; : String a3=(String) o[3]; : int a33=Integer.parseInt(a3); : 先把Object轉成各自的基本型態再強制轉型成int, : 字串給的不是數字不知道該如何轉成int,上面的語法是錯的, : 能想到到的就是轉成unicode,只是不知道該如何寫, : 想請教各位高手,謝謝。 隨手亂寫~ public static void main(String args[]) throws Exception{ Object objects[]= { new Integer(1), new Double(1.2), new Float(1.6), new String("app"), new String("0x36"), new Long(5566) }; for(int n=0; n<objects.length; n++){ Object object = objects[n]; if(object instanceof Integer){ // skip }else if(object instanceof Double){ objects[n] = new Integer(((Double)object).intValue()); }else if(object instanceof Float){ objects[n] = new Integer(((Float)object).intValue()); }else if(object instanceof String){ try{ objects[n] = new Integer(Integer.decode((String)object)); }catch(NumberFormatException e){ System.out.println(e.getMessage() + "cant parse to Integer"); objects[n] = new Integer(0); } }else if(object instanceof Long){ objects[n] = new Integer(((Long)object).intValue()); }else{ System.out.println("unknown datum :" + object.getClass().toString()); objects[n] = new Integer(0); } } for(Object object: objects){ System.out.println((int)object); } } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 111.241.42.190 ※ 編輯: realmeat 來自: 111.241.42.190 (10/09 22:55)
文章代碼(AID): #1ILMkCI- (java)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):
文章代碼(AID): #1ILMkCI- (java)