Java - println question

2006-12-15 6:31 pm
Can anyone tell me how do I print the array as bellow statement?

int [] array = new int[4];
..........

System.out.println(array[0], array[1], array[2], array[3]);

Thanks

回答 (2)

2006-12-15 6:42 pm
✔ 最佳答案
println prints strings only. However, Java will coerce a numeric variable into a string if you do a string operation. For example, your statement will work simply adding a null string ("") or a space (" ") at the beginning, and spacing out the numbers, such as:
String space=" ";
System.out.println(space+array[0]+space+array[1]+space+array[2]+space+ array[3]);

You can be more elegant by using a for loop and print the numbers on separate lines:
String space=" ";
for(int i=0;i<4;i++)System.out.println(space+array[i]);
2006-12-15 6:38 pm
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
}


收錄日期: 2021-04-12 20:10:50
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20061215000051KK00666

檢視 Wayback Machine 備份