Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

apter 9. PC #8. 8. Sum of Numbers in a String (page 610) Write a program that as

ID: 3597747 • Letter: A

Question

apter 9. PC #8. 8. Sum of Numbers in a String (page 610) Write a program that asks the user to enter a series of numbers separated by commas. Here are two examples of valid input: 7,9,10,2,18,6 8.777,10.9,11,2.2,-18,6 The program should calculate and display the sum of all the numbers. Input Validation 1. Make sure the string only contains numbers and commas (valid symbols are '0'-'9', '-', '.', and ','). 2. If the string is empty, a messages should be displayed, saying that the string is empty.

Explanation / Answer

Hi friend, you have not mentioned about Programming Language.

I have implementd in JAVA.

import java.util.InputMismatchException;

import java.util.Scanner;

public class SumofNumber {

  

   public static void main(String[] args) {

      

       Scanner sc = new Scanner(System.in);

      

       System.out.println("Enter strings of number seperated by comma: ");

       String line = sc.nextLine();

       sc.close();

      

       if(line.trim().isEmpty()) {

           System.out.println("string is empty");

       }else{

          

           // breaking string by comma

           Scanner scan = new Scanner(line);

           scan.useDelimiter(",");

          

           double sum = 0;

          

           try{

              

               while(scan.hasNext()) {

                  

                   double d = Double.parseDouble(scan.next().trim());

                  

                   sum = sum + d;

               }

              

               System.out.println("Sum of the number: "+sum);

               scan.close();

              

           }catch(InputMismatchException ex) {

               scan.close();

               System.out.println("Input is not valid");

           }

       }

   }

}

/*

Sample run:

Enter strings of number seperated by comma:

7,9,10,2,18,6,8.777,10.9,11,2.2,-18,6

Sum of the number: 72.87700000000001

*/