Re: Unknown number of inputs
- From: "Randolf Richardson" <kingpin+nntp@xxxxxxxxxxxxxxx>
- Date: Tue, 30 Jan 2007 23:32:31 GMT
On Mon, 29 Jan 2007 22:26:50 -0800, Andrew Thompson <andrewthommo@xxxxxxxxx> wrote:
On Jan 30, 5:14 pm, "f2prateek" <f2prat...@xxxxxxxxx> wrote:[sNip]
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 ) {
....
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/
.
- References:
- Unknown number of inputs
- From: f2prateek
- Re: Unknown number of inputs
- From: Andrew Thompson
- Unknown number of inputs
- Prev by Date: Re: Unknown number of inputs
- Next by Date: Re: Is there an easy way to find the right class?
- Previous by thread: Re: Unknown number of inputs
- Next by thread: Re: Unknown number of inputs
- Index(es):
Relevant Pages
|