Chapter 9. PC #8. 8. Sum of Numbers in a String (page 610) Write a program that
ID: 3710882 • Letter: C
Question
Chapter 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.
Please it is important to use the EXIT_SENTINENTAL = "QUIT"; and the numbers must use 2 decimals. In java programming language
Explanation / Answer
import java.util.Scanner;
public class HelloWorld{
public static void main(String []args){
Scanner scan = new Scanner(System.in);
final String EXIT_SENTINENTAL = "QUIT";
System.out.println("Enter a series of numbers separated only by commas or type QUIT to exit:");
String s = scan.nextLine();
while(!s.equals(EXIT_SENTINENTAL)) {
if(s.equals("")) {
System.out.println("Empty string.");
} else {
String nums[]= s.split(",");
double sum = 0;
for(int i=0;i<nums.length;i++) {
sum+=Double.parseDouble(nums[i]);
}
System.out.printf("The sum of those numbers is %.2f ",sum);
}
System.out.println("Enter a series of numbers separated only by commas or type QUIT to exit:Enter a series of numbers separated only by commas or type QUIT to exit:");
s = scan.nextLine();
}
}
}
Output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.