【问题标题】:Java - How do I call a method within a switch statement?Java - 如何在 switch 语句中调用方法?
【发布时间】:2019-10-04 07:35:25
【问题描述】:

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

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

    }
}

【问题讨论】:

  • 我在这段代码中看不到switch:我看到casedefault,但看不到语句从哪里开始。
  • average 是 main 方法中的局部变量。您不能在该方法之外使用它。一种解决方法是将其声明移到方法之外,在类主体中并使其成为static
  • 很难判断,因为您的代码不完整,但从 averageLength() 函数返回 average 的值可能会有所帮助
  • 我已经上传了整个代码

标签: java variable-declaration


【解决方案1】:

您粘贴的代码存在一些问题 - 其中一些已在之前的 cmets/answers 中发现,但为了完整起见,我也会在此处列出:

  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: ");
     }
    }
    

【讨论】:

    【解决方案2】:

    从显示的代码中,您可以调用不带参数的“averageLength()”,而它需要两个参数:单词数组及其计数。

    该调用还包含一个错字(“g”缺失)。

    因此,编译器无法找到该函数,因为它引用了一个实际上并不存在的函数。

    另外,在“averageLength()”的两个参数中,单词数组是未使用的,您重新扫描单词而不是使用通过开关的其他情况建立的列表。 这可能是一个逻辑错误。

    【讨论】:

      【解决方案3】:

      请修复:

      1. 在方法main(): averageLenth();averageLength(words, count);
      2. 在方法averageLength()double sum;double sum = 0;

      【讨论】:

        【解决方案4】:
        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);
        
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-08-26
          • 2014-01-17
          • 2016-06-27
          • 1970-01-01
          • 2011-05-16
          • 1970-01-01
          • 1970-01-01
          • 2020-06-25
          相关资源
          最近更新 更多