java - 如何在 Scanner 中使用枚举类型

标签 java enums java.util.scanner bufferedreader

非常感谢您在广告方面的帮助!

使用枚举类型的扫描仪时出现错误。但是,我不允许在此任务中使用 Buffer (InputStreamReader)。最好的解决办法是什么?

我收到以下错误:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Cannot switch on a value of type String for source level below 1.7. Only convertible int values or enum variables are permitted

at ui.Application.runCLI(Application.java:33)
at ui.Application.main(Application.java:13)

代码:

package ui;

导入java.util.Scanner;

公共(public)类应用程序{

static String command;

public enum Command {
    CONNECT, DISCONNECT, SEND, LOGLEVEL, HELP, QUIT, EXIT
}

private static void run(Scanner sc) {
    // String command; // ready for the input

    boolean done = false; // ready for the menu loop
    while (!done) { // keep on until done

        System.out
                .println("Milestone1: Connection and interation with TCP server");
        System.out
                .println("-------------------Please select on of the commandso-------------------------------------");
        System.out.println("connect");
        System.out.println("disconnect");
        System.out.println("send");
        System.out.println("logLevel");
        System.out.println("help");
        System.out.println("quit");
        System.out.println("exit");

        command = sc.nextLine(); // take user input         
        Command cmd=null;
        try{
        cmd=Command.valueOf(command.toUpperCase());
        }
        catch (IllegalArgumentException e){
            System.out.println("Invalid input");
            return;
        }
        switch (cmd) {

        case EXIT: // exit menu
            done = true;// condition for breaking the loop
            break;

        case CONNECT:

            System.out.print(" IP adress: ");

            try {
                String userInput = sc.toString(); // user Input

                System.out.println(" Port: ");

                int userInput1 = sc.nextInt();// user Input

                if (userInput1 >= 0) {

                    System.out.println(" EcoClient>" + " " + command + " "
                            + userInput + " " + userInput1);
                } else {
                    System.out
                            .println("Entered value for Port is negative number or IP adress length < 7 || > 15, not in n.n.n.n format ");
                }

            }

            catch (Exception e) {// throw exception in case of illogical
                                    // input
                System.out.println("\nBad input, please try again ");
                sc.nextLine(); // remove leftover "\n"
            }

            break;

        case DISCONNECT:

            System.out.println(" EcoClient>" + " " + command);

            break;

        case SEND:

            System.out
                    .println("Please enter " + " Hello World " + "phrase");
            try {
                String userInput = sc.toString(); // user Input
                System.out.println(" EcoClient>" + " " + command + " "
                        + userInput);

            }

            catch (Exception e) {// throw exception in case of illogical
                                    // input

                System.out.println("\nBad input, please try again ");
                sc.nextLine(); // remove leftover "\n"
            }
            break;

        case LOGLEVEL:
            try {
                System.out.println(" EcoClient>" + " " + command + "< "
                        + "current log status" + " >");
            }

            catch (Exception e) {// throw exception in case of illogical
                                    // input

                System.out.println("\nBad input, please try again ");
                sc.nextLine(); // remove leftover "\n"

            }
            break;

        case HELP:
            try {
                System.out
                        .println("Following set of commands provide following functionalities:"
                                + " connect: establishes connection to the eco server "
                                + "disconnect: disconnects from the server and receives confirmation message "
                                + "send: sends the message to the server "
                                + "logLevel: prints out current log status"
                                + "quit: quits and notifies user about program shut down "
                                + "exit: cancel the input");

            }

            catch (Exception e) {// throw exception in case of illogical
                                    // input

                System.out.println("\nBad input, please try again ");
                sc.nextLine(); // remove leftover "\n"
            }
            break;

        case QUIT:

            try {
                System.out.println(" EcoClient> " + command);

            }

            catch (Exception e) {// throw exception in case of illogical
                                    // input

                System.out.println("\nBad input, please try again ");
                sc.nextLine(); // remove leftover "\n"

            }
            break;

        default:
            System.out.println("Does not recognise "
                    + "the input, pl. try again");

        }

    }
}

public static void main(String[] args)  {

    Scanner sc = new Scanner(System.in);// will take user input

    run(sc);

}

}

最佳答案

sc.nextLine() 返回一个字符串。您需要使用静态方法 Command.valueOf(String) 将其转换为 Command 实例(您正在使用 switch)它解析字符串并返回匹配的 Command 实例。

这是基础知识:

command = sc.nextLine(); // take user input
Command cmd = null;
try {
    cmd = Command.valueOf(command.toUpperCase());
} catch (IllegalArgumentException e) {
    System.out.println("Invalid input, sorry."); //This is given on invalid input.  Put whatever type of error message you want here.
    return;
}
switch (cmd) {
//...

关于java - 如何在 Scanner 中使用枚举类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26457227/

相关文章:

Java 字符串扫描器下一行输入字符串不符合预期

java - 为什么我的 display() 方法没有打印出所有 ArrayList 元素?

java - 在 Android 中解析 XML 流

java - Spring Junit Hibernate @Transactional - 无 session

java - 如何将每个 AsyncTask 类放在单独的文件中?

java - 在 JDBC 中使用日历对象

swift - 为什么这个带有两个枚举的 Swift switch 语句不详尽?

c# - 如何防止枚举中的重复值?

java - 使用 wsgen 时是否可以保留枚举值?

java - 使用具有字符串模式的扫描器对字符串进行标记化