Java打印整个数组,带有","符号?

Jon*_*ale 4 java arrays

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...

为什么在最后一个数组项后添加另一个','?我该如何预防呢?

anu*_*ava 8

为什么不打电话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)

  • 我很高兴你做出了改变(+1).但为什么不使用`substring`?当我们想要做的就是删除第一个和最后一个字符时,正则表达式是过度的. (2认同)

dav*_*tto 7

// 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)