views:

71

answers:

3

The method does not show any error but I am unable to use it in main method to display the list.

    if (userinput.equalsIgnoreCase("push") )
    {   calc.push(value);
        calc.displaylist();
         System.out.println(calc.getValues());
    }
    else if (userinput.equalsIgnoreCase("mult"))
    {  calc.push(calc.mult());
       calc.getValues(); }

how to use this method ... instead i used a methos called display list and that works but i need to know how to use my getValues method. both the methods are as below :

Double[] getValues()
    {

      Double[] array = new Double[values.size()];
      return values.toArray(array);
    }

    void displaylist()
    {
        for(Double d : values)
          System.out.println(d);
    }
A: 

You can use a static method called toString(Object[]) in the java.util.Arrays class.

Ash
A: 

Well your displaylist() method contains a for-each loop that will iterate over the contents of a collection. The collection to iterate over is on the right side of the ':'. You've got a method that returns a collection - specifically, a Double[] - so you can call your getValues() method in place of the collection.

So, try this:

void displaylist()
{ 
    for(Double d : getValues()) System.out.println(d);
}
Shakedown
A: 

I'm trying to understand the question - Let me restate it and see if I got it or not:

  1. You have an object that has a Collection (probably a List) of values called values.
  2. You have a method, getValues(), which returns an array containing all of the values in values.
  3. You would like to print out all of the values in values.
  4. You are required (homework?) to use the getValues() method when printing out values in values. (If you're not required to use getValues(), then I don't see what's wrong with the displaylist() method that you already wrote.)
  5. You tried to just call System.out.println() on the array that you got from getValues(), but that just printed something awful like "[Ljava.lang.Double;@39172e08".

Did I get it?

Unfortunately, even with all that, I'm not sure what to suggest because I don't know what you want the printed out version to look like.

Should the values be separated by commas? If so, Ash's answer will do this for you. Should each one be on its own line? If so, Shakedown's answer will do this for you. Should the values just be separated by spaces? If so, then you can modify Shakedown's answer to use print(d + " ") instead of println(d).

Joe Carnahan