8. Sum of Numbers in a String Write a program that asks the user to enter a seri
ID: 3738063 • Letter: 8
Question
8. Sum of Numbers in a String 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 display the sum of all the numbers. 9. Sum of Digits in a String Write a program that asks the user to enter a series of single digit numbers with nothing separating them. The program should display the sum of all the single digit numbers in the string. For example, if the user enters 2514, the method should return 12, which is the sum of 2, 5, 1, and 4. The program should also display the highest and lowest digits in the string. (Hint: Convert the string to an array.)Explanation / Answer
SumOfNos.java
import java.util.Scanner;
public class SumOfNos {
public int sumOfNosSeperatedByComma(String str)
{
int sum=0;
//Converting the String to String array
String arr[]=str.split(",");
for(int i=0;i<arr.length;i++)
{
//calculating the sum
sum+=Integer.parseInt(arr[i]);
}
return sum;
}
public void sumOfIndividualDigits(String str)
{
int sum=0,num;
int high,low;
//Converting String to char array
char arr[]=str.toCharArray();
high=Integer.parseInt(String.valueOf(arr[0]));
low=Integer.parseInt(String.valueOf(arr[0]));
//Calculating sum and find high and lowest digit
for(int i=0;i<arr.length;i++)
{
num=Integer.parseInt(String.valueOf(arr[i]));
sum+=num;
if(high<num)
high=num;
if(low>num)
low=num;
}
//Displaying the output
System.out.println("Sum = "+sum);
System.out.println("Highest Digit = "+high);
System.out.println("Lowest Digit = "+low);
}
}
____________________
Test.java
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
String str;
/*
* Creating an Scanner class object which is used to get the inputs
* entered by the user
*/
Scanner sc = new Scanner(System.in);
//Getting the input entered by the user
System.out.print("Enter Nos seperated by comma :");
str=sc.nextLine();
SumOfNos son=new SumOfNos();
//Displaying the output
System.out.println("Sum = "+son.sumOfNosSeperatedByComma(str));
//Getting the input entered by the user
System.out.print("Enter numbers :");
str=sc.next();
son.sumOfIndividualDigits(str);
}
}
_______________________
Output:
Enter Nos seperated by comma :7,9,10,2,18,6
Sum = 52
Enter numbers :2514
Sum = 12
Highest Digit = 5
Lowest Digit = 1
___________Thank You
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.