I need the code below to use a enhannced for statement to sum the double values
ID: 3634425 • Letter: I
Question
I need the code below to use a enhannced for statement to sum the double values passed by the command-line argument. I also need to use the static method parseDouble to convert a String to a double value. Here is the code I have. This is a Java question. The problem i am having is that is gives an out of bounds error, any help would be appreciated.
public class SumDouble
{
public static void main(String [] args)
{
int arrayLength = Integer.parseInt(args[0]);
int array[] = new int[arrayLength];
double initialValue = Double.parseDouble(args[1]);
double increment = Double.parseDouble(args[2]);
for(int counter:array)
initialValue+=increment;
System.out.println(initialValue);
}
}
Explanation / Answer
public static void main(String[] args) { // TODO Auto-generated method stub if(args.length !=2) System.out.println(" please enter no more than 2numbers"); else { double sum = 0.0; int arrayLength = Integer.parseInt(args[0]); double [] myArray = new double [ arrayLength ]; double num1 = Double.parseDouble((args[1])); for(String s: args){ sum += Double.parseDouble(s); } System.out.println("Sum: "+sum); }