Write a program that asks the user to enter a series of numbers
separated by commas. Here is an example of valid input:
7,9,10,2,18,6
The program should calculate and print the sum of all the
numbers.
Sample Run
java NumberSum
Enter·numbers·separated·by·commas:1,2,3↵
6↵
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main
{
public static void main(String[] args)
{
double sum = 0; //calculate sum
String number; // string to input
Scanner sc = new Scanner(System.in); // scanner for input
System.out.println("Enter·numbers·separated·by·commas:");
number = sc.nextLine(); //input number
StringTokenizer strTokenizer = new StringTokenizer(number, ",");
//break string into different tokens
while (strTokenizer.hasMoreTokens())
{
sum = Double.parseDouble(strTokenizer.nextToken())+sum;
//parse those tokens from string to double to calculate sum
}
System.out.print("Sum: "+ sum);
}
}
OUTPUT:
IF YOU HAVE ANY QUERY PLEASE COMMENT DOWN BELOW
PLEASE GIVE A THUMBS UP
Get Answers For Free
Most questions answered within 1 hours.