how to use my getvalues() method in main to print the list
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"))
{ 开发者_Python百科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);
}
You can use a static method called toString(Object[])
in the java.util.Arrays
class.
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);
}
I'm trying to understand the question - Let me restate it and see if I got it or not:
- You have an object that has a
Collection
(probably aList
) of values calledvalues
. - You have a method,
getValues()
, which returns an array containing all of the values invalues
. - You would like to print out all of the values in
values
. - You are required (homework?) to use the
getValues()
method when printing out values invalues
. (If you're not required to usegetValues()
, then I don't see what's wrong with thedisplaylist()
method that you already wrote.) - You tried to just call
System.out.println()
on the array that you got fromgetValues()
, 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)
.
精彩评论