System.out.print("Please select a game: ");
for (String s : gamesArray) {
System.out.print(s + ", ");
}
Run Code Online (Sandbox Code Playgroud)
输出:
Please select a game: spin, tof, Press any key to exit...
我除外的输出:
Please select a game: spin, tof Press any key to exit...
为什么在最后一个数组项后添加另一个','?我该如何预防呢?
为什么不打电话Arrays#toString(array):
System.out.print("Please select a game: %s%n",
Arrays.toString(gamesArray).replaceAll("(^\\[)|(\\]$)", ""));
Run Code Online (Sandbox Code Playgroud)
或者为了避免正则表达式:
String tmp = Arrays.toString(gamesArray);
System.out.print("Please select a game: %s%n", tmp.substring(1, tmp.length()-1));
Run Code Online (Sandbox Code Playgroud)
// iterate throght array
for ( int i = 0; i < gamesArray.length; i++ ) {
// get the element
String s = gamesArray[i];
// print it
System.out.print( s );
// test if the current element is not the last (array size minus 1)
if ( i != gamesArray.length - 1 ) {
// if it is not the last element, print a comma and a space.
System.out.print( ", " );
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
258 次 |
| 最近记录: |