39.0k views
1 vote
2. Using the Enhanced for Statement, write an application that uses an enhanced for statement to sum the double values passed by the command-line arguments. [Hint: Use the static method parseDouble of class Double to convert a String to a double value.] This is sample run of your program: The·sum·of·the·double·values·passed·in·from·the·command·line·is·0.0↵

User Preme
by
6.5k points

1 Answer

4 votes

Answer:

Here is the program:

public class DoubleValue

{ public static void main(String[] args) { //start of the main function

double sum = 0.0; // initialize double type sum by 0.0

//for statement to sum the double values passed by the command-line //arguments

for (String str : args) {

sum += Double.parseDouble(str);

//returns double representation of the passed str argument and takes the //sum of these double values }

System.out.printf("The sum of the double values passed in from the command line is %.1f\\", sum); } }

//prints the above message with output 0.0

Step-by-step explanation:

The above program has a static method parseDouble of class Double to convert a string str to a double value and the for statement is used to sum the double values passed by command line arguments. This sum is stored in sum variable and is displayed in the output. The program along with its output is attached.

If you want to get the input from the user you can use the following code. Just use the Scanner class to take input from the user.

import java.util.Scanner;

public class DoubleValue

{ public static void main(String[] args) {

//two string type variables

String str1;

String str2;

//scans and reads input from user

Scanner input = new Scanner(System.in);

System.out.println("Enter value of str1: ");

str1 = input.next();

System.out.println("Enter value of str2: ");

str2 = input.next();

double sum = 0.0;

//sum double values and parseDouble function is used to convert string to //double value

sum += Double.parseDouble(str1) + Double.parseDouble(str2);

System.out.printf("The sum of the double values passed in from the command line is %.1f\\", sum); } } //prints result of the sum

2. Using the Enhanced for Statement, write an application that uses an enhanced for-example-1
2. Using the Enhanced for Statement, write an application that uses an enhanced for-example-2
User DatHydroGuy
by
6.3k points