简体   繁体   English

Java - 如何在 switch 语句中调用方法?

[英]Java - How do I call a method within a switch statement?

averageLength gets all the words the user has entered in the previous case and gets the average amount of words. averageLength获取用户在前一种情况下输入的所有单词,并获取单词的平均数量。 The switch statement sits under the main method (not shown here) but when I try to implement case 3 to get the average, it does not work because average is not declared under the main method, its under averageLength . switch 语句位于 main 方法下(此处未显示),但是当我尝试实现案例 3 以获取平均值时,它不起作用,因为average未在main方法下声明,它在averageLength下。 How can I fix this?我怎样才能解决这个问题? Thanks谢谢

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

    }
}

From the code shown, you call "averageLength()" with no parameters, whereas it requires two: the array of words and their count.从显示的代码中,您可以调用不带参数的“averageLength()”,而它需要两个:单词数组及其计数。

The call also contains a typo (the "g" is missing).该调用还包含一个错字(“g”缺失)。

So, the function cannot be found by the compiler, since it references a function that doesn't actually exist.因此,编译器无法找到 function,因为它引用了实际上不存在的 function。

Additionally, of the two parameters of "averageLength()", the array of words is unused, you rescan for words instead of using the list established through the other cases of the switch.此外,在“averageLength()”的两个参数中,单词数组未使用,您重新扫描单词而不是使用通过开关的其他情况建立的列表。 This is probably a logic error.这可能是一个逻辑错误。

Please, fix:请修复:

  1. In method main() : averageLenth();在方法main()中: averageLenth(); to averageLength(words, count); averageLength(words, count);
  2. In method averageLength() : double sum;在方法averageLength() : double sum; to double sum = 0; double sum = 0;
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);

    }
}

There are a few issues with the code you've pasted - some of which have already been identified in previous comments/answers, but I'll list them here as well for completeness:您粘贴的代码存在一些问题 - 其中一些已在之前的评论/答案中确定,但为了完整起见,我也会在此处列出它们:

  1. Typo in the name of averageLenth - change to averageLength .以 averageLenth 的名义averageLenth - 更改为averageLength Your code will not compile because of this.因此,您的代码将无法编译。
  2. The signature of averageLength(String[] words, int count) is not being honoured at the call site - change to averageLength(words, count) at the call site inside the switch.调用站点不遵守averageLength(String[] words, int count)的签名 - 在交换机内的调用站点更改为averageLength(words, count)
  3. The implementation of averageLength is incorrect - your implementation is not infact iterating over the array of words and computing the average but appears to be asking the scanner for the next input. averageLength的实现是不正确的——您的实现实际上并没有遍历单词数组并计算平均值,而是似乎在向扫描仪询问下一个输入。 I've changed the impelentation in the code below to comput the average by iterating over the word array.我已经改变了下面代码中的实现,通过迭代单词数组来计算平均值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将此 if-else 语句转换为 java 中的 switch 语句? - How do I convert this if-else statement into a switch statement in java? 如何从Java类中的另一个方法调用我的方法? - How do I call my method from another method I have within my class in Java? java - 如何在java中的for语句中自主切换变量名? - How do I autonomously switch variable names in a for statement in java? 如何在 Java 中的 switch 语句中添加同义词? - How do I add synonyms to a switch statement in Java? 如何在Java中正确执行二进制switch语句? - How can I correctly do a binary switch statement in java? Java:如何将switch语句的大小写转移到单独的文件? - Java: How do I shift the cases of a switch statement to separate file? 使用方法中的 switch 语句将字母转换为数字 - Java - Converting a letter to a number using a switch statement within a method - Java 我如何在方法内部使用switch语句,以便该方法可以返回由switch语句获取的char值? - How do i use switch statement inside a method such that the method can return a char value which is acquired by the switch statement inside it? 如何在事件监听器的语句中调用函数? - How do I call a function from within a statement in the event listener? Java 中的 Do While 语句中的方法? - Method within Do While statement in Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM