2012-09-12 3 views
1

내 프로그램은 "commandparameter"형식의 사용자 키보드 명령을 공백으로 읽습니다. 다음 명령이 "exit"이 될 때까지 개별 명령을 계속 수행합니다. 또한 사용자가 망가 뜨리면 프로그램에 오류가 표시되지만 계속 명령을 요청해야합니다 (완료되지 않았다고 생각하는 기능).연속 입력 명령

다음 코드는이 기능을 구현하는 좋은 방법입니까? 명령, 정크 입력 등을 사용하여 Enter 키를 누르는 것만으로 사용자를 처리 할 수 ​​있습니까? 무엇보다, 이것을 구현하는 더 나은 관용적 방법이 있는지 알고 싶습니다.

String command = ""; 
String parameter = ""; 
Scanner dataIn = new Scanner(System.in); 

while (!command.equals("exit")) { 
    System.out.print(">> "); 

    command = dataIn.next().trim(); 
    parameter = dataIn.next().trim(); 
    //should^these have error handling? 

    if (command.equals("dothis")) { 
     //do this w/ parameter.. 
    } else if (command.equals("dothat")) { 
     //do that w/ parameter.. 
    } //else if... {} 
     else { 
     system.out.println("Command not valid."); 
    } 
} 

System.out.println("Program exited by user."); 

참고 : 나는 예외 처리가 무엇인지 하나의 개념없이이 클래스를했다, 그래서 그 지역의 모든 포인터는 크게 감사합니다 :)

+0

작은 노트 :'next()'가 유효한 호출인지 확인하기 위해'dataIn.next()'를 호출하기 전에 항상'dataIn.hasNext()'를 호출해야합니다. 일반적으로 입력 명령을 구문 분석 할 때 루프 헤드는 'while (dataIn.hasNext())'또는 'while (dataIn.hasNextLine())'입니다. –

+0

그래서'while (! command.equals ("exit") && dataIn.hasNextLine())'? – James

답변

0

이것은 입력 루프를 구현하는 간단한 방법입니다 :

Scanner sc = new Scanner(System.in); 

for (prompt(); sc.hasNextLine(); prompt()) { 

    String line = sc.nextLine().replaceAll("\n", ""); 

    // return pressed 
    if (line.length == 0) 
     continue; 

    // split line into arguments 
    String[] args = line.split(" ");  

    // process arguments 
    if (args.length == 1) { 
     if (args[0].equalsIgnoreCase("exit")) 
      System.exit(0); 
     if (args[0].equalsIgnoreCase("dosomething")) 
      // do something 
    } else if (args.length == 2) { 
     // do stuff with parameters 
    } 
} 

prompt()은 프롬프트를 여기에 출력한다고 가정합니다.

+0

prompt()는 단지'System.out.println (">>");'일까요? – James

+0

거의. 그것은'System.out.print (">>");' –

+0

입니다. 또한 args []가 2가 아닌 길이 1이되는 이유는 무엇입니까? return args [0]과 args [1]을 쪼개지 않아야합니까? – James

관련 문제