Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Different variable type for Vector or array? Similar to Structure in C 3

Status
Not open for further replies.

asiavoices

Programmer
Sep 20, 2001
90
CA
Hello all,

I was wondering how I could define a multi-dimensional Vector or array that has different variable types? Similar to a Structure in C?

And how I could access the elements via indexing?

For example:

1. I'd like to enter an items' ID (int), description (string), price (float?) and taxable-state (boolean)

2. User's enter the info and its loaded in the Vector/Array. How is this done?

3. After all items have been entered, how do loop to display the Vector or array and their elements?

I understand that the size of an array cannot be changed so I would guess that Vector would be the best solution, correct? (For the user to keep adding the data)

thanks all,

Christopher
 
I suggest you take a look at the JavaDocs for the
Code:
Vector
class. Basically a
Code:
Vector
allows you to add any
Code:
Object
to it (so you don't have to define a
Code:
Vector
of any particular type). So to make a multi-dimensional
Code:
Vector
you just add a
Code:
Vector
to the base
Code:
Vector
. Unfortunately this means that primitives (int, float, etc.) must use wrapper classes in order to be put into a
Code:
Vector
or any other
Code:
Collection
.

As far as how to add elements and loop through a
Code:
Vector
, this is the type of information you should be finding from the JavaDocs.
 
Hi Wushutwist,

I am very new to Java and know very little about Vectors & how objects can interact with this Class.

Could you be so kind as to show me how the "code" of the wrapper or at least the initial implementation looks like.

Thanks,

Christopher

 
I suggest that you use class to implement the struct function.Then you can add the class's instance to a Vector.

Regards! IPO_z@cmmail.com
Garbage in,Garbage out
 
I suggest you get a good beginner's book on Java. In the meantime I will give you an example to start you off. Example:
Code:
/* variables to add to Collection */
int one = 1;
String two = "two";
float three = 3.0f;

/* Collection to add variables to, we will use a Vector */
Collection collection = new Vector();

/* Wrap int and add to Collection */
collection.add(new Integer(one));

/* String is an object, no need to wrap */
collection.add(two);

/* Wrap float and add to Collection */
collection.add(new Float(three));

/* Get Iterator and loop through Collection */
Iterator ite = collection.iterator();
while(ite.hasNext()) {
  /* Get each object and print to screen */
  Object o = ite.next();
  System.out.println(o);
}
 
Hello again Wushutwist,

Thanks for the great start. I had a hunch too (as IPOz suggested - thank you!)that I should use a Class as a "structure" .

Its just that I wasn't sure how they could be tied in or associated into a Vector.

One more quick question here (for my own clarification). In your code, it displays...

Collection collection = new Vector();

Am I correct to assume that the "Collection" (leading uppercase) is the name of the Class that contains the variables you've outline earlier? (ie. int one = 1; String two = "two";
float three = 3.0f;)

So if I were to rewrite to say...

Public class MyStuff

{
int one = 1;
String two = "two";
float three = 3.0f;

......

}

MyStuff mycollection = new Vector();

Translated... this would mean that I created a new vector object named mycollection whose type is derived from the MyStuff class.

Is this correct? I hope so ... I'm a bit slow so please be patient with me LOL

Thanks,

Christopher



 
No.
Code:
Collection
is the base interface for the Collections API and the SuperInterface of the
Code:
Vector
class. I only used that because it is good practice in case you wanted to change from using a
Code:
Vector
to say an
Code:
ArrayList
. Now that we are on the subject an
Code:
ArrayList
would most likely be a better choice since you will take a slight performance hit with a
Code:
Vector
. The
Code:
Vector
class is
Code:
synchronized
by default so you take a hit if you don't really need the synchronization.

As far as your code, I'll rework it and give you another example, this time using an
Code:
ArrayList
.
Code:
public class Test {

/* Inner class for convenience of this example */
class MyStuff {
  public int one;
  public String two;
  public float three;
} 

public static void main(String args[]) {

  /* Create MyStuff */
  MyStuff myObject = new MyStuff(); //default constructor
  myObject.one = 1;
  myObject.two = "two";
  myObject.three = 3.0f;

  /* Collection, we will use an ArrayList */
  Collection collection = new ArrayList();

  /* Add myObject to Collection */
  collection.add(myObject);

  /* Get Iterator and loop through Collection */
  Iterator ite = collection.iterator();
  while(ite.hasNext()) {
    /* Get each object and cast to MyStuff */
    MyStuff o = (MyStuff)ite.next();
    System.out.println(o.one);
    System.out.println(o.two);
    System.out.println(o.three);
  }
}
}
Note: I left everything in MyStuff as public for ease of the example (I don't want to overload you). In practice you should be a good little programmer and follows the laws of Data Encapsulation. This example should compile and execute unless I have made a typo.
 
Thanks wushutwist,

Your suggestion was excellent. I tried another way and it almost worked but unfortunately I have an error when I try to compile it. The error is:

"non-static variable theTotal cannot be referenced from a static context"
theTotal += rs.getPrice();
^

(the whole code is attached below)

Basically, the Item Class have 3 fields: Name, Price and isTax (y/n).

As it loops through, I want to be able to add the prices to a total variable called theTotal (double type).


Here's my Item Class that stores the info:


/* ===================================
* Item.java =
* =================================== */

public class Item {

private String itemName;
private double itemPrice;
private char itemTax;

public Item(String theName, double thePrice, char theTax)
{
setItemName(theName);
setItemPrice(thePrice);
setItemTax(theTax);
}

public void setItemName(String theName)
{
itemName = theName;
}

public void setItemPrice(double thePrice)
{
itemPrice = thePrice;
}

public void setItemTax(char theTax)
{
itemTax = theTax;
}


public String getName()
{
return itemName;
}

public double getPrice()
{
return itemPrice;
}

public char getTax()
{
return itemTax;
}

} // end of Item Class scope



Here's my Asia Class that displays the results:


/* ===================================
* Asia.java =
* =================================== */


import java.util.*;

public class Asia

{

public double theTotal;

public static void main(String[] args)
{

Vector myStuff = new Vector();

Item c1 = new Item("Item A here ....", 99.0d, 'y');
Item c2 = new Item("item B here ....", 100.0d, 'n');
Item c3 = new Item("Item C here ....", 200.0d, 'n');

myStuff.add(c1);
myStuff.add(c2);
myStuff.add(c3);


/* ===============================
= display the record set =
=============================== */

for (int i=0; i < myStuff.size(); i++)
{
Item rs = (Item) myStuff.elementAt(i);
he error --> theTotal += rs.getPrice();
System.out.print( &quot;Name: &quot; + rs.getName() + &quot;\t\tPrice: &quot; + rs.getPrice() + &quot;\t\tTaxable? &quot; + rs.getTax() + &quot;\n&quot;);
} // end of for loop

} // end of main() method

} // end of Asia Class


Any ideas?

Also, based on your experience... what would be the best approach to use that would allow the user to continually enter info until they done (ie. keep on adding until they are done by entering a certain key)

I know that is problably a DO WHILE loop but I just wanted to know how to create the object variables and store them into a list or array, etc. of some sort and then do the calculations and print our the results... that's all.

Thanks again,

Christopher




 
Here is what it should look like:
Code:
import java.util.*;

public class Asia {
    
  private double total;
  
  /* Constructor */
  public Asia() {
    total = 0;
  }
  
  public setTotal(double total) {
    this.total = total;
  }

  public double getTotal() {
    return total;
  }

  public static void main(String[] args) {
    Asia() asia = new Asia();
    ArrayList myStuff = new ArrayList();           
        
    Item c1 = new Item(&quot;Item A here ....&quot;, 99.0d, 'y');
    Item c2 = new Item(&quot;item B here ....&quot;, 100.0d, 'n');
    Item c3 = new Item(&quot;Item C here ....&quot;, 200.0d, 'n');
        
    myStuff.add(c1);
    myStuff.add(c2);
    myStuff.add(c3);

    Iterator ite = myStuff.iterator();
    while (ite.hasNext()) {
      Item data = (Item)ite.next();
      asia.setTotal(asia.getTotal + data.getPrice());
      System.out.print( &quot;Name: &quot; + data.getName()+ &quot;\t\tPrice: &quot; + data.getPrice() + &quot;\t\tTaxable? &quot; + data.getTax() + &quot;\n&quot;);
    } // End of while
  }  // End of main
}  // End of Asia class
Again, I suggest using an ArrayList and you should almost always be using an Iterator to loop through your Collections.
 
Wow you have been a great help wushutwist ! Thank you ...

I'll look into the collections a bit more.

I'll experiment and hope it works..

Cheers,

C
 
You'll either have to move the decleration for theTotal into the main() function or declare theTotal as static:

public static double theTotal;


OR... You'd have to instantiate class Asia inside of the main() function like this:

Asia myAsia = new Asia;
myAsia.theTotal += rs.GetPrice();

Class and Instance variables/methods/fields can be a real headache... :)
 
One more thing... I tried compiling it and it gave me an error that it couldn't find the getTotal method...

Here's the message:

Asia.java [60:1] cannot resolve symbol
symbol : variable getTotal
location: class Asia
asia.setTotal(asia.getTotal + data.getPrice());
^

mmm.. its there... here's the code again...



/* ================================
= Asia.java =
================================ */

import java.util.*;


public class Asia

{
public static double theTotal;
private double total;


/* ======== Asia's Constructor ===== */

public Asia()
{
total = 0;
}


/* ======== setTotal method ===== */

public void setTotal(double total)
{
this.total = total;
}


/* ======== getTotal method ===== */

public double getTotal()
{
return total;
}



/* ======== main method ===== */

public static void main(String[] args)
{

Asia asia = new Asia();
ArrayList myStuff = new ArrayList();

Item c1 = new Item(&quot;Item A here ....&quot;, 99.0d, 'y');
Item c2 = new Item(&quot;item B here ....&quot;, 100.0d, 'n');
Item c3 = new Item(&quot;Item C here ....&quot;, 200.0d, 'n');

myStuff.add(c1);
myStuff.add(c2);
myStuff.add(c3);

Iterator ite = myStuff.iterator();
while (ite.hasNext())
{
Item data = (Item)ite.next();
asia.setTotal(asia.getTotal + data.getPrice());
System.out.print( &quot;Name: &quot; + data.getName()+ &quot;\t\tPrice: &quot; + data.getPrice() + &quot;\t\tTaxable? &quot; + data.getTax() + &quot;\n&quot;);
}

}
}

Do you know why? you are write that Class and Instance variables/methods/fields are headaches... Any good books you can recommend?

thanks,

C

 
My typo, it should be asia.getTotal(). I didn't have the () in there.
 
Oops... you're right... didn't see that one..

I've just bought another java book :) Java Collections

Thanks,

Christopher
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top