Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print out elements from an array with a comma between elements except the last word

Tags:

I am printing out elements from an array list and want to have a comma between each word except the last word. Right now I am doing it like this:

for (String s : arrayListWords) {     System.out.print(s + ", "); } 

As you understand it will print out the words like this: one, two, three, four, and the problem is the last comma, how do I solve this? All answers appreciated!

like image 971
Eri. Avatar asked Aug 16 '13 18:08

Eri.


People also ask

How do you print out an array of elements?

We cannot print array elements directly in Java, you need to use Arrays. toString() or Arrays. deepToString() to print array elements. Use toString() method if you want to print a one-dimensional array and use deepToString() method if you want to print a two-dimensional or 3-dimensional array etc.

How do you print the last element of an array?

// If you want print the last element in the array. int lastNumerOfArray= myIntegerNumbers[9]; Log. i("MyTag", lastNumerOfArray + ""); // If you want to print the number of element in the array.

How do you remove the last element of an array in Java?

We can use the remove() method of ArrayList container in Java to remove the last element. ArrayList provides two overloaded remove() method: remove(int index) : Accept index of the object to be removed. We can pass the last elements index to the remove() method to delete the last element.


2 Answers

Print the first word on its own if it exists. Then print the pattern as comma first, then the next element.

if (arrayListWords.length >= 1) {     System.out.print(arrayListWords[0]); }  // note that i starts at 1, since we already printed the element at index 0 for (int i = 1; i < arrayListWords.length, i++) {       System.out.print(", " + arrayListWords[i]); } 

With a List, you're better off using an Iterator

// assume String Iterator<String> it = arrayListWords.iterator(); if (it.hasNext()) {     System.out.print(it.next()); } while (it.hasNext()) {     System.out.print(", " + it.next()); } 
like image 113
Sotirios Delimanolis Avatar answered Oct 13 '22 00:10

Sotirios Delimanolis


I would write it this way:

String separator = "";  // separator here is your ","  for (String s : arrayListWords) {     System.out.print(separator + s);     separator = ","; } 

If arrayListWords has two words, it should print out A,B

like image 20
Mav Avatar answered Oct 12 '22 23:10

Mav