Does Java print an entire array with a ","?

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 exclude is:

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

Why does it add another "," after the last element of the array? How to prevent this?

+4
source share
7 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)); 
+8
source
 // 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( ", " ); } } 
+7
source

Why does it add another "," after the last element of the array?

Since there is nothing special about the last element, you add at the end of each element.

How to prevent this?

You can try using the usual for -loop and add only if the index you specified is not the last index of the array. Equivalently, you can add before each element except the first one and you will get the same effect.

 int len = gamesArray.length; if (len > 0) System.out.println(gamesArray[0]); for (int i = 1; i < len; i++) System.out.print(", " + gamesArray[i]); 
+2
source

Can you use the Guava library? If so, this is one line of code:

 String result = Joiner.on(", ").join(gamesArray); System.out.println(result); 
+2
source

The last comma is, because you print a comma after each element.

You can fix this by rewriting the for loop like this:

 for(int i=0;i<gameArray.length;i++){ System.out.print(gameArray[i]); if(i!=gameArray.length-1){ System.out.println(", "); } } 
+1
source

Another way to handle this (especially well if you know that the array will never be empty) is to write the first element before the loop, and then write the loop , <element> .

+1
source

You need to check if there are more elements in your array before printing "," to avoid the appearance of one after the last name of the game.

 final Iterator<String> iterator = Arrays.asList(gamesArray).iterator(); while(iterator.hasNext()) { System.out.print(iterator.next()); if(iterator.hasNext()) { System.out.print(", "); } } System.out.println(); 
0
source

Source: https://habr.com/ru/post/1487953/


All Articles