Java - Как я могу вызвать метод в инструкции switch? - PullRequest
0 голосов
/ 04 октября 2019

averageLength получает все слова, введенные пользователем в предыдущем случае, и получает среднее количество слов. Оператор switch находится под основным методом (здесь не показан), но когда я пытаюсь реализовать случай 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);

            switch (choice) {
                case 1: 
                    System.out.println("Add a word");
                    aWord = sc.next();
                    count = add(words, count, aWord);
                    break;

                case 2:
                    System.out.println("Display words");
                    System.out.println("We have an array of " + words.length + " integers: " + Arrays.toString(words));
                    break;

                case 3:
                    averageLenth();              
                    break;

                default:
                    System.out.println("Invalid responce");

            }
        } while (choice >= 0 && choice < 4);

    }
}

Ответы [ 4 ]

0 голосов
/ 04 октября 2019

Есть несколько проблем с кодом, который вы вставили - некоторые из них уже были определены в предыдущих комментариях / ответах, но я приведу их здесь также для полноты:

  1. Опечатка на имя averageLenth - изменить на averageLength. Из-за этого ваш код не будет компилироваться.
  2. На сайте вызовов не учитывается подпись averageLength(String[] words, int count) - измените на averageLength(words, count) на сайте вызовов внутри коммутатора.
  3. Реализация 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) {
    }
    
    
    private static void averageLength(String[] words, int count) {
        int sum=0;
    
        for(int word =0; word < count; word++){
         int wordLength = words[word].length();
         sum += wordLength;
        }
    
        double averageWorldLength = sum/count;
        System.out.println("Average word length = " +averageWorldLength;
    }
    
    
    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 {
            displayMenuOptions();
            choice = sc.nextInt();
            System.out.println("choice = " + choice);
    
            switch (choice) {
                case 1:
                    System.out.println("Add a word");
                    aWord = sc.next();
                    count = add(words, count, aWord);
                    break;
    
                case 2:
                    System.out.println("Display words");
                    System.out.println("We have an array of " + words.length + " integers: " + Arrays.toString(words));
                    break;
    
                case 3:
                      averageLength(words, count);
                      break;
                default:
                    System.out.println("Invalid responce");
    
            }
        } while (choice >= 0 && choice < 4);
    }
    
    private static void displayMenuOptions() {
        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: ");
     }
    }
    
0 голосов
/ 04 октября 2019

Пожалуйста, исправьте:

  1. В методе main(): averageLenth(); до averageLength(words, count);
  2. В методе averageLength(): double sum; до double sum = 0;
0 голосов
/ 04 октября 2019
import java.util.Scanner;
import java.util.Arrays;

/**
 * Word Manager
 *
 * @author Harry
 */
public class WrodManager {

    /**
     * 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 = 0;

        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);

            switch (choice) {
            case 1:
                System.out.println("Add a word");
                aWord = sc.next();
                count = add(words, count, aWord);
                break;

            case 2:
                System.out.println("Display words");
                System.out.println("We have an array of " + words.length + " integers: " + Arrays.toString(words));
                break;

            case 3:
                averageLength(words, count);
                break;

            default:
                System.out.println("Invalid responce");

            }
        } while (choice >= 0 && choice < 4);

    }
}
0 голосов
/ 04 октября 2019

Из показанного кода вы вызываете «averageLength ()» без параметров, тогда как для этого требуется два: массив слов и их количество.

Вызов также содержит опечатку ("g" - этоотсутствует).

Таким образом, функция не может быть найдена компилятором, поскольку она ссылается на функцию, которая на самом деле не существует.

Кроме того, из двух параметров "averageLength ()", массив слов не используется, вы пересканируете слова вместо того, чтобы использовать список, созданный в других случаях коммутатора. Это, вероятно, логическая ошибка.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...