我想检查一个字符串序列,计算平均字符串长度,并计算有多少字符串高于平均长度。
到目前为止,在我的代码中,它只读取整数,字符串也有字符。那么我如何更改我的代码,使其适用于字符串而不是 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");
}
}
此处仅发布更改。其余代码保持不变。
- 数组的数据类型从 int 更改为字符串
- console.nextInt() 更改为 console.next(),它将在返回时读取字符串
- 遍历 String 数组,并将单个字符串的长度与字符串的平均长度进行比较。
这就是所需要的。
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++;
}
}
您可以更改以下内容改变
console.nextInt()
自 console.nextLine()
sum += strings[i]
自 sum += strings[i].length
if (strings[i] > average)
自 if (strings[i].length > average)