我想检查一个字符串序列,计算平均字符串长度,并计算有多少字符串高于平均长度。
到目前为止,在我的代码中,它只读取整数,而字符串也有字符。那么如何更改我的代码以使其适用于字符串而不是 int。我知道第一步是取出 nextInt 方法并将其更改为适用于字符串以及代码中的其他 int 变量。有人能帮我吗?
// 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");
}
}