Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java print a whole array, with a " , " sign?

Tags:

java

arrays

System.out.print("Please select a game: ");
for (String s : gamesArray) {       
    System.out.print(s + ", "); 
}

Output:

Please select a game: spin, tof, Press any key to exit...

The output I am excepting:

Please select a game: spin, tof
Press any key to exit...

Why is it adding another ',' after the last array item? How do I prevent it?

like image 573
Jony Kale Avatar asked Nov 29 '22 12:11

Jony Kale


1 Answers

Why not just call Arrays#toString(array):

System.out.print("Please select a game: %s%n", 
                  Arrays.toString(gamesArray).replaceAll("(^\\[)|(\\]$)", ""));

OR to avoid regex:

String tmp = Arrays.toString(gamesArray);
System.out.print("Please select a game: %s%n", tmp.substring(1, tmp.length()-1));
like image 131
anubhava Avatar answered Dec 04 '22 16:12

anubhava