[英]Convert specific int array to String
我有這樣的變量int數組
int[] sample = new int[];
sample[0] = 1;
sample[1] = 2;
String two = sample[1].toString(); <==== i have problem with this
System.out.println(two);
如何解決? 我無法將int [1]的值顯示為字符串。
你做不到
int i = 2;
String two = i.toString(); // or sample[1].toString();
因為int
是原始類型 ,而不是對象。 當您使用int[] sample
數組時,請注意,雖然sample
是一個對象,但sample[1]
只是一個int
,因此還是原始類型。
相反,你應該做
int i = 2;
String two = String.valueOf(i); // or String.valueOf(sample[1]);
但是,如果您的問題只是將值打印到System.out
,則它具有println(int x)
方法,因此您只需執行
int i = 2;
System.out.println(i); // or System.out.println(sample[1]);
現在,如果要打印數組的完整表示,請執行
System.out.println(Arrays.toString(sample));
更改此行:
String two = sample[1].toString(); <==== i have problem with this
對此:
String two = String.valueOf(sample[1]);
@ericbn提出的建議還有另一種方法。 您可以從int基本類型創建Integer
對象,然后使用toString
方法獲取其String值:
Integer I = new Integer(i);
System.out.println(I.toString());
另一個解決方案可以是-
String two = sample[1]+"";//concatenate with empty String
System.out.println(two);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.