0

我想检查一个字符串序列,计算平均字符串长度,并计算有多少字符串高于平均长度。

到目前为止,在我的代码中,它只读取整数,而字符串也有字符。那么如何更改我的代码以使其适用于字符串而不是 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");
    }

}
4

2 回答 2

0

此处仅发布更改。其余代码保持不变。

  1. 数组的数据类型从 int 更改为 String
  2. console.nextInt() 更改为 console.next() 将在返回时读取字符串
  3. 循环遍历字符串数组并将单个字符串的长度与字符串的平均长度进行比较。

这就是所有需要的。

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++;
            }
        }
于 2016-04-26T05:57:14.827 回答
-1

您可以将以下更改更改
console.nextInt()console.nextLine()

sum += strings[i]sum += strings[i].length

if (strings[i] > average)if (strings[i].length > average)

于 2016-04-26T05:41:37.053 回答