Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / April 2008

Tip: Looking for answers? Try searching our database.

iterating through an array of String's

Thread view: 
thufir - 20 Apr 2008 09:50 GMT
For lab2 at http://members.shaw.ca/Java2611/ I need to load data (which
should be an array of Strings) from DATA -- that's not the assignment,
but it's a requirement that the data is loaded in this particular
fashion.  It's supposed to not even really be a problem, because we're
supposed to (from my notes):

hard code the data in the program,
private final String[] GUEST_DATA = {...}

use the constructor

Guest guest1 = new Guest(GUEST_DATA[0]); // will grab row 0

At the moment, I'd be happy to print out DATA, but I want to be able to
iterate through DATA, assigning one row at a time to the data array,
basically doing what's above.

Yes, I'll be reviewing arrays, and it sounds straightforward, but I don't
see why the output is hexadecimal (the object's memory address?).

Any "pointers" would be appreciated:

thufir@arrakis:~/foo$ javac ArrayOfStrings.java
thufir@arrakis:~/foo$ java ArrayOfStrings
[[Ljava.lang.String;@1a46e30
[[Ljava.lang.String;@1a46e30
thufir@arrakis:~/foo$ cat ArrayOfStrings.java
public class ArrayOfStrings
{

       public static String[] data;

       private final static String[][] DATA = {
               {"00", "01", "02", "03"},
               {"10", "11", "12", "13"},
               {"20", "21", "22", "23"},};

       public static void loadData() {
               for (int i=0; i<2; i++) {
                       data = DATA[0];
                       System.out.println(DATA);
               }
       }

       public static void main (String[] args) {
               loadData();
       }
}
thufir@arrakis:~/foo$

thanks,

Thufir
Roedy Green - 20 Apr 2008 11:04 GMT
>    data = DATA[0];
>                        System.out.println(DATA);

println is not smart enough to print an entire array. You need an
extra layer of loop to print out the elements one at a time with print
with a println at the end of the row.

If you feed it an array it just prints the address of the array, --
useless except in debugging.
Signature


Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Thufir - 30 Apr 2008 11:43 GMT
> >    data = DATA[0];
> >                        System.out.println(DATA);
>
> println is not smart enough to print an entire array. You need an
> extra layer of loop to print out the elements one at a time with print
> with a println at the end of the row.

A similar situation (here, just a method):

    public static void print(Object[] array){
        List list = Arrays.asList(array);
        for(Object element : list){
            System.out.println(element.toString());
        }
    }

I haven't fully tested it out, but I've tried passing a String[] and
am still getting memory pointers.

-Thufir
Roedy Green - 20 Apr 2008 11:05 GMT
>  private final static String[][] DATA = {
>                {"00", "01", "02", "03"},
>                {"10", "11", "12", "13"},
>                {"20", "21", "22", "23"},};

to iterate through a doubly dimensioned array, see

http://mindprod.com/jgloss/array.html#MATRIXGOTCHAS
Signature


Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

thufir - 21 Apr 2008 08:58 GMT
>>  private final static String[][] DATA = {
>>                {"00", "01", "02", "03"},
[quoted text clipped - 4 lines]
>
> http://mindprod.com/jgloss/array.html#MATRIXGOTCHAS

I've looked around, but haven't found the information I was looking for
yet.  Strictly looking at the syntax for assigning a row of ADDRESS_DATA
to the address object, is there a more compact syntax?

thufir@arrakis:~/bcit-comp2611-lab2$
thufir@arrakis:~/bcit-comp2611-lab2$ cat src/a00720398/labs/Task.java
//Task.java

//this class is required to be the "meat" of lab2

package a00720398.labs;
import a00720398.data.*;
import java.util.*;

public class Task
{
       private ArrayList<Guest> guests;

       private Guest guest;

    //these three objects should consolidated to one object:
       Address address;
       ContactInfo contactInfo;
       Name name;

       //it's required to load data from these arrays

                 private final String[][]

       GUEST_DATA = {
       { "Lee", "Brenda", "(604) 636-1000", "b.lee@bcit.ca" },
       { "Sullivan", "Sam", "604-873-7011", "Sam777@hotmail.com" },
       { "Johansen", "Lars", "(604) 636-1000", "Lars147@gmail.com" }},

       ADDRESS_DATA = {
       { "3700 Willingdon Avenue", "Burnaby", "British Columbia",
       "V5G 3H2", "Canada" },
       { "453 West 12th Avenue", "Vancouver", "BC", "V5Y 1V4",
        "Canada"  },
       { "1000 Lougheed Highway", "Coquitlam", "British Columbia",
       "V3K 3T5", "" } };

       //creates new instances of each Guest attribute
       //It might be better to treat name, contactInfo and address
       //as mutatable.  Not a major point.
       public Guest newGuest(int row){
               name = new Name(GUEST_DATA[row][0], GUEST_DATA[row][1]);
               contactInfo = new ContactInfo(GUEST_DATA[row][2],
               GUEST_DATA[row][3]);

               //apparently there's a trick to assign an entire
               //row with one go?
               address = new
                Address(ADDRESS_DATA[row][0],ADDRESS_DATA[row][1],
               
               ADDRESS_DATA[row][2],ADDRESS_DATA[row][3]
               ,ADDRESS_DATA ,[row][4]);
               Guest guest = new Guest(name,contactInfo,address);
               return guest;
       }

       public void loadArray() {
               guests = new ArrayList<Guest>();
               for (int i=0; i<3; i++) {
                       guest = newGuest(i);
                       guests.add(guest);
               }
               System.out.println(guests);
       }
}
thufir@arrakis:~/bcit-comp2611-lab2$

thanks,

Thufir
thufir - 21 Apr 2008 11:34 GMT
> I've looked around, but haven't found the information I was looking for
> yet.  Strictly looking at the syntax for assigning a row of ADDRESS_DATA
> to the address object, is there a more compact syntax?
[...]
>         //creates new instances of each Guest attribute //It might be
>         better to treat name, contactInfo and address //as mutatable.
>         Not a major point.
>         public Guest newGuest(int row){

Aha, now it works:
       /*creates a new instance of guest from GUEST_DATA and
       ADDRESS_DATA for a given row (guest id number?)
       this method is more complex than it should be
       but accomplishes the requirement of:
       Write a separate class that creates three guests from a data
array.
       folding Name, Address and ContactInfo into one class
       would simplify Lab2 enormously.  */
       public Guest newGuest(int row){
               name = new Name(GUEST_DATA[row]);
               contactInfo = new ContactInfo(GUEST_DATA[row]);  //
totally redundant
               address = new Address(ADDRESS_DATA[row]);
               Guest guest = new Guest(name,contactInfo,address);
               return guest;
       }

I swear that I'd tried to pass a row before and it didn't work, but,
anyhow, now it does :)
voorth - 21 Apr 2008 11:51 GMT
> > I've looked around, but haven't found the information I was looking for
> > yet.  Strictly looking at the syntax for assigning a row of ADDRESS_DATA
[quoted text clipped - 25 lines]
> I swear that I'd tried to pass a row before and it didn't work, but,
> anyhow, now it does :)

Try
 java.util.Arrays.toString(data)

This will transform {"A", "B", "C"} to "[A, B, C]"
Lew - 21 Apr 2008 12:12 GMT
thufir wrote:
>>         public Guest newGuest(int row){
>>                 name = new Name(GUEST_DATA[row]);
[quoted text clipped - 7 lines]
>> I swear that I'd tried to pass a row before and it didn't work, but,
>> anyhow, now it does :)

The trick is to have a constructor that takes a String [] as a parameter.

> Try
>   java.util.Arrays.toString(data)
>
> This will transform {"A", "B", "C"} to "[A, B, C]"

This is completely not going to help.  Then the constructor would have to
parse the String, instead of directly accessing the array elements.

Signature

Lew

Ian Kidder - 22 Apr 2008 14:44 GMT
> For lab2 athttp://members.shaw.ca/Java2611/I need to load data (which
> should be an array of Strings) from DATA -- that's not the assignment,
[quoted text clipped - 49 lines]
>
> Thufir

if only i knew a good mentat joke . . .

you are getting memory pointers from the run because you only have one
for loop and you are walking through a 2-d array. the output is
basically DATA[0], DATA[1]. to walk through a two dimensional array,
you need nested for loops. try this:

public class ArrayOfStrings34
{

       public static String data;

       private final static String[][] DATA = {
               {"00", "01", "02", "03"},
               {"10", "11", "12", "13"},
               {"20", "21", "22", "23"},};

       public static void loadData() {
               for (int i=0; i<DATA.length; i++) {
                 for (int j = 0; j < DATA[0].length; j++) {
                   System.out.println(DATA[i][j]);
                 }
               }
       }

       public static void main (String[] args) {
               loadData();
       }

}
thufir - 23 Apr 2008 05:06 GMT
> if only i knew a good mentat joke . . .

I should collect some!

> you are getting memory pointers from the run because you only have one
> for loop and you are walking through a 2-d array. the output is
> basically DATA[0], DATA[1]. to walk through a two dimensional array, you
> need nested for loops.

Right, thanks for explaining what the result was!  What I actually wanted
to do was:

    public static String TWO_D_ARRAY = {
    { "00", "01", "02" },
    { "10", "11", "12" },
    { "20", "21", "22" }},

    public static String[] data;

    data = TWO_D_ARRAY(0);  //grabs 00, 01, 02

to just grab a single row.  seems silly to me, but this was, essentially,
a requirement of the lab (to grab a row without explicitly iterating).

I think it's rather arcane, but it makes me wonder if there's some
similar "magical" technique for grabbing column.

-Thufir
Lew - 23 Apr 2008 05:19 GMT
> Right, thanks for explaining what the result was!  What I actually wanted
> to do was:
>
>     public static String TWO_D_ARRAY = {

Variable names by convention begin with a lower-case letter and use camelCase
for the rest.

You named this variable an array, but didn't declare it as one.  This
statement will never compile.

>     { "00", "01", "02" },
>     { "10", "11", "12" },
[quoted text clipped - 3 lines]
>
>     data = TWO_D_ARRAY(0);  //grabs 00, 01, 02

Array notation uses square brackets, not parentheses.  As written, your
statement will not compile.

> to just grab a single row.  seems silly to me, but this was, essentially,

Why?  It's perfectly sensible and quite useful.

> a requirement of the lab (to grab a row without explicitly iterating).
>
> I think it's rather arcane,

Not at all.  Since Java doesn't support two-dimensional arrays, it makes
perfect sense.  String [] [] doesn't declare an array of Strings, it declares
an array of String [].

> but it makes me wonder if there's some similar "magical" technique for grabbing column.

Nope.  And there's absolutely nothing "magical" about grabbing rows - you
actually aren't grabbing rows, you are grabbing array elements.

Signature

Lew



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.