2014-10-20 1 views
1

감사합니다.스캐너에서 enum 유형을 사용하는 방법

enum 유형의 스캐너를 사용할 때 오류가 발생합니다. 그러나이 작업에서는 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;

공용 클래스 응용 프로그램 {

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

} 

}

+0

main''의 선언에 단어'static'을 넣어하는 것을 잊지 마세요 : 여기

은 기본이다 정적으로도. –

+0

정적을 추가해도 문제가 해결되지 않음 감사합니다. –

+0

stacktrace에서 위의'run' 대신'runCLI'를 언급합니까? –

답변

2

sc.nextLine()는 문자열을 반환합니다. 문자열을 구문 분석하고 일치하는 Command 인스턴스를 반환하는 정적 메서드 Command.valueOf(String)을 사용하여 Command (switch을 사용하는) 인스턴스로 변환해야합니다. 또한, 중`run`를 호출하기 전에 클래스를 인스턴스화 또는 선언`run` -

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) { 
//... 
+0

동일한 오류가 계속 발생하지만 Jim Garrison에게 감사합니다. –

+0

"main"스레드의 예외 java.lang.Error : 컴파일되지 않은 컴파일 문제 : \t 1.7 이하의 소스 레벨에 대해 String 유형의 값을 켤 수 없습니다. 만 INT 값 또는 열거 형 변수 컨버터블 –

+0

@NadiaS 당신은'스위치를 바꿨나요 ui.Application.runCLI에서 \t (Application.java:33) ui.Application.main에서 \t (Application.java:13) (명령을 허용)'스위치 (cmd)'? – Pokechu22