averageLength获取用户在上一个案例中输入的所有单词并获取平均单词数。switch 语句位于 main 方法下(此处未显示),但是当我尝试实现案例 3 以获得平均值时,它不起作用,因为它没有average在main方法下声明,而是在averageLength. 我怎样才能解决这个问题?谢谢
import java.util.Scanner;
import java.util.Arrays;
/**
* Word Manager
*
* @author Harry
*/
public class WordManager {
/**
* Adds the word to the next empty space in the array, if there is space.
* Returns the new size of the array.
*/
public static int add(String[] words, int count, String word) {
if (count < words.length) {
words[count] = word;
count++;
} else {
System.out.println("The array is full");
}
return count;
}
/** Displays the words in the collection as a comma separated list. */
public static void printList(String[] words, int count) {
}
public static void averageLength(String[] words, int count) {
Scanner sc = new Scanner(System.in);
double average;
double sum;
while (sc.hasNext()) {
String userInput = sc.next();
double charNum = userInput.length();
sum = charNum + sum;
count++;
if (count > 0) {
average = sum / count;
System.out.println("Average word length = " + average);
}
}
}
public static void main(String[] args ) {
Scanner sc = new Scanner(System.in);
String[] words = new String[20];
int count = 0;
String aWord;
int choice;
do {
System.out.println("\t MENU:");
System.out.println("1. Add a word");
System.out.println("2. Display words:");
System.out.println("3. Display average word length");
System.out.println("4. Quit");
System.out.println("Enter option: ");
choice = sc.nextInt();
System.out.println("choice = "+choice);
慕码人2483693
慕姐4208626
至尊宝的传说
明月笑刀无情
相关分类