1,105,406 Community Members

A neater way to print elements in an array?

Member Avatar
Bud4java
Newbie Poster
13 posts since Mar 2005
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Is there a "neater" way to code the following? (It prints the 5 data elements in an array.)

System.out.println("All the values in the array are: ");
System.out.println(+ array1[0]);
System.out.println(+ array1[1]);
System.out.println(+ array1[2]);
System.out.println(+ array1[3]);
System.out.println(+ array1[4]);

Thanks,
Bud

Member Avatar
Narue
Bad Cop
12,139 posts since Sep 2004
Reputation Points: 5,693 [?]
Q&As Helped to Solve: 1,537 [?]
Skill Endorsements: 81 [?]
Team Colleague
 
1
 

>Is there a "neater" way to code the following?

System.out.println ( "All the values in the array are: " );
for ( T x: array1 )
  System.out.println ( x );

Change T to whatever the type of the array is. Or, if you aren't up to the latest version of Java:

System.out.println ( "All the values in the array are: " );
for ( int i = 0; i < array1.length; i++ )
  System.out.println ( array1[i] );
Member Avatar
Bud4java
Newbie Poster
13 posts since Mar 2005
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Thanks...exactly what I was looking for!

Bud

Member Avatar
rotten69
Master Poster
747 posts since May 2011
Reputation Points: 20 [?]
Q&As Helped to Solve: 45 [?]
Skill Endorsements: 15 [?]
 
-2
 

a neater way of getting values from an array! Good work, buddy.

System.out.println ( "All the values in the array are: " );
for ( T x: array1 )
  System.out.println ( x );

Thanks.

Member Avatar
peter_budo
Code tags enforcer
7,935 posts since Dec 2004
Reputation Points: 2,502 [?]
Q&As Helped to Solve: 1,028 [?]
Skill Endorsements: 66 [?]
Moderator
Featured
 
0
 

@rotten69 was it worth to reopen 6 year old thread? (Created 02-05-05)

Thread closed, before another time-traveler arrival

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article