/* Craig Persiko CS 111A
MethodToInputArray example
in-class exercise
Inputs 3 numbers from a user,
using a method to return them in an array.
*/
import java.util.Scanner;
class MethodToInputArray
{
public static void main(String[] args)
{
double[] nums;
nums = inputArray(3);
System.out.println("Here are the numbers:");
for(int i=0; i < nums.length; i++)
System.out.print(nums[i] + " ");
}
static double[] inputArray(int numElements)
{
Scanner s = new Scanner(System.in);
double[] a = new double[numElements];
for(int i=0; i < numElements; i++)
{
System.out.print("Please enter a number: ");
a[i] = s.nextDouble();
}
s.nextLine(); // remove leftover newline char
return a;
}
}
/* Sample Output:
-bash-3.2$ java MethodToInputArray
Please enter a number: 7.5
Please enter a number: 1.33
Please enter a number: 6
Here are the numbers:
7.5 1.33 6.0
*/
syntax highlighted by Code2HTML, v. 0.9