I want to examine a sequence of strings, compute the average string length, and count how many strings are above the average length.
So far, in my code, it only reads ints, and a string also has characters. So how do I change my code so that it works for strings and not int. I know that the first step is take out the nextInt methods and change it to work for strings as well as the other int variables in the code. Can someone help me?
// examine a sequence of strings
// compute the average string length
// count how many strings are above the average length
import java.util.*;
public class StringArrayTest {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("What is the number of strings? ");
int numStrings = console.nextInt();
String[] strings = new String[numStrings];
// record strings to find average length
int sum = 0;
for (int i = 0; i < numStrings; i++) {
System.out.println("Number of strings from string " + (i + 1) + ": ");
String nextLine = console.next();
strings[i] = nextLine;
sum += strings[i].length;
}
double average = (double) sum / numStrings;
// count strings above average length
int above = 0;
for (int i = 0; i < strings.length; i++) {
if (strings[i].length() > average) {
above++;
}
}
// report results
System.out.println();
System.out.println("Average length of strings: " + average);
System.out.println(above + " strings above average length");
}
}
Only changes are being posted here. Rest of the code remains the same.
That's all that is required.
String[] strings = new String[numStrings];
...
for (int i = 0; i < numStrings; i++) {
System.out.println("Number of strings from string " + (i + 1) + ": ");
String nextLine = console.next();
strings[i] = nextLine;
sum += strings[i].length();
}
...
for (int i = 0; i < strings.length; i++) {
if (strings[i].length() > average) {
above++;
}
}