In: Computer Science
Provide the Java code to compute the sum, average, maximum number and minimum number if I have a string sentence of double numbers. Assume that the length of the string sentence is not known. It can be of any length.
To split a string based on the comma character use the following.
String sentence = "A,B,C,D,E";
String[] stringsArray = receivedSentence.split(",");
Then stringsArray is an array of five elements such that:
stringsArray[0] = 'A'
stringsArray[1] = 'B'
stringsArray[2] = 'C'
stringsArray[3] = 'D'
stringsArray[4] = 'E'
stringsArray.length will equal 5.
package newone;
public class doubleStats {
public static void main(String[] args) {
String sentence =
"1.1,4.5,6,7,12,-56,34.34,562.4,322";
String[] stringsArray =
sentence.split(",");
double[] arr = new
double[stringsArray.length];
double max =
Double.parseDouble(stringsArray[0]);
double min =
Double.parseDouble(stringsArray[0]);
double n=0,total=0,avg;
for(String s:stringsArray) {
n+=1;
double num =
Double.parseDouble(s);
total+=num;
if(num>max)
max=num;
if(num<min)
min=num;
}
avg = total/n;
System.out.println("Total:
"+total);
System.out.println("Average:
"+avg);
System.out.println("Maximum:
"+max);
System.out.println("Minimum:
"+min);
}
}