Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to display values in an array

 
Viidhya Kishore
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am having a String[] array.

I need to display all its values separated by commas.

Like Iam having values like 1,2,3,4.

Vidhya
 
fred rosenberger
lowercase baba
Bartender
Posts: 12086
29
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you need to loop through your array, and print them as you go or build a big long string, then print that when you're done.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or you could use

System.out.println(Arrays.asList(theArray))

but that will enclose your list in [] marks.
 
Norm Radder
Ranch Hand
Posts: 728
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Capture the output and substring out the data minus the []s
 
vaibhav mishra
Ranch Hand
Posts: 168
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
do it in Java 5 way

use enhanced for loop
let string array you want to print is

A[]

then code will be


[edit]Corrected code tags. CR[/edit]
[ July 23, 2008: Message edited by: Campbell Ritchie ]
 
vedha vas
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Shriya Kishore ,

Try this way :

String s[] = {new String("1"),new String("2"),new String("3"),new String("4"),new String("5")};
String str = Arrays.asList(s).toString();
System.out.println(str.substring(1, str.length()-1));
 
Rob Spoor
Sheriff
Pie
Posts: 20495
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Instead of Arrays.asList(s).toString(), use Arrays.toString(s). These toString methods, added in Java 5.0, do the same thing without creating the List object.
 
Viidhya Kishore
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks everyone for your valuable suggestions.
I stuck around wit Rob's and it is good now.

Thanks once again.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic