Re: Unknown number of inputs



On Mon, 29 Jan 2007 22:26:50 -0800, Andrew Thompson <andrewthommo@xxxxxxxxx> wrote:
On Jan 30, 5:14 pm, "f2prateek" <f2prat...@xxxxxxxxx> wrote:

I want to make a program to print the average of the numbers entered
by the user,but how do i accept the numbers from the user,if the
number of numbers enetred by him or not known to me??

"Enter a series of numbers, one to a line.
Type 'a' to calculate the average"

public double calculateAverage( double[] allValues ) {
....
[sNip]

That would require stuffing everything into an array[] prior to calling. Although that's a perfectly valid solution, a variable number of arguments (printf() is probably the most common application in the C/C++ programming world) could also be supported with a declaration like:

public double calculateAverage( double... allValues ) { ... }

The JVM will just pass the variable number of arguments as an array[], so no code changes will need to be made internally. This can also work for a static main() declaration, as follows (code not tested):

public static main(String... args) {
System.out.println("Argument count: " + args.length);
for (String temp: args) // This is a Perl-style "foreach" loop
System.out.println(" " + temp);
}

I hope someone finds that to be of interest. If so, see how variable arguments (a.k.a. "varargs" or "var args") are used in the following heavily documented code example:

http://www.internationalnetwork.com/java/examples/DisplayFile.java

--
Randolf Richardson - kingpin+nntp@xxxxxxxxxxxxxxx
The Lumber Cartel, local 42 (Canadian branch)
http://www.lumbercartel.ca/
.



Relevant Pages

  • Re: Need help on PHP for MPE/ix
    ... If one item is an array, it must be declared as such in the list ... So, please show us the declaration of the record buffer, and its ... Of Pavan Kumar Rati ... Need help on PHP for MPE/ix ...
    (comp.sys.hp.mpe)
  • Re: Difference between C and advanced C
    ... static and type qualifiers in parameter array declarators ... trailing comma allowed in enum declaration ... additional predefined macro names ... additional strftime conversion specifiers ...
    (comp.lang.c)
  • Re: avoiding writing an interface blocks
    ... the reason this needs an explicit interface is because of the ... example, an array, and not specify the argument types. ... type, period, with any kind of declaration. ... C-type pointers, including to ...
    (comp.lang.fortran)
  • Re: Does the order of declarations matter?
    ... > subroutine sub ... > Or must the declaration for N appear before the declaration ... parameter or array bound shall be specified in a prior ...
    (comp.lang.fortran)
  • Re: legality of forward declaration
    ... how do you interpret the following paragraph from the C99 Standard ... Array declarators ... A declaration of a parameter as ??array of type?? ... it is the compiler that is in error. ...
    (comp.lang.c)