In: Computer Science
This is Java
In this problem we will write a program that asks the user to enter a) The user's first name and b) a series of integers separated by commas. The integers may not include decimal points nor commas. The full string of numbers and commas will not include spaces either, just digits and commas. An example of valid input string is: 7,9,10,2,18,6
The string must be input by the user all at once; do not use a loop to read each number one at a time. The purpose of this assignment is to learn to use the String methods. The program will calculate and display the following data:
Dear Student ,
As per the requirement submitted above , kindly find the below solution.
Here a new java program with name "Main.java" is created, which contains following code.
Main.java :
import java.util.*;
public class Main
{
public static void main(String[] args) {
//creating object of Scanner class
Scanner sc=new Scanner(System.in);
//asking user to enter first name
System.out.print("Enter First Name
: ");
//reading first name
String username=sc.next();
//asking user to enter numbers
seprated by commas
System.out.print("Enter Numbers
separated by commas : ");
//reading numbers
String numString=sc.next();
//spliting string
String[] strSplit =
numString.split(",");
//declared variable to store sum ,
count and average
int sum=0,count=0;
double average=0;
//using for loop to make sum of
numbers in the string
for (String num :strSplit)
{
sum=sum+Integer.parseInt(num);
count++;//increment count
}
//calculate average
average=sum/count;
String avg=String.format("%.1f",
average);
//display details
System.out.println("Username :
"+username);//display username
System.out.println("Sum :
"+sum);//display sum
System.out.println("Count :
"+count);//display count
System.out.println("Average :
"+avg);//display average
}
}
======================================================
Output : Compile and Run Main.java to get the screen as shown below
Screen 1 :Main.java
NOTE : PLEASE FEEL FREE TO PROVIDE FEEDBACK ABOUT THE SOLUTION.