2013-02-02 2 views
0

잘못된 입력을 우아하게 처리하고 사용자에게 다시 입력하라는 메시지를 표시하면서 사용자 터미널에서 여러 입력을 받아야하는 응용 프로그램을 개발 중입니다. 필자의 전나무는 while 루프를 사용하여 본문이 입력을 받아 유효성을 확인하고 유효한 입력을받을 때 플래그를 설정하는 것이 좋습니다. 이 플래그는 응용 프로그램이있는 단계를 표시하고 다음에 필요한 입력 유형을 결정하며 루프의 종료 조건으로도 사용됩니다.터미널에서 System.in 이벤트 잡기

작동하는 동안 이것은 다소 우아하지 않은 것처럼 보입니다. 구문 분석 할 새 입력이 있음을 나타 내기 위해 return 키를 누를 때마다 호출되는 함수를 작성할 수있는 방법이 있는지 궁금합니다.

public class Interface { 
    public void receiveInput(final String input){ 
     // Parse 'input' for validity and forward it to the correct part of the program 
    } 
} 

의 라인 아마도이 extending 일부 Java 클래스에 의해 달성과 중 하나를 다시 구현 될 수 있습니다 함께 뭔가 일반적으로 이러한 이벤트를 처리 할 기능,하지만 그것은 아마도 내 C++ 배경 이야기입니다.

건물 및 단위 테스트에 필요한 외부 라이브러리를 제외한 다른 라이브러리를 사용할 수 없습니다. 콘솔에서 읽는 동안

답변

2

당신의 readline 함수를 호출하여

BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 

와 BufferedReader로

을 사용할 수 있습니다, 그것은 새로운 라인 처리합니다 : 당신은 확실히 클래스를 가질 수

String readLine = br.readLine(); 

을하는 존재는 것에 정보를 읽고 계속하는 기능입니다. 이 도움이

Please Enter inputs for the questions asked 
$showlist 
List 1 
List 2 
List 3 
$shownewlist 
New List 1 
New List 2 
$exit 
Finished 

희망 : 여기

가 참고 여기

public class TestInput { 


    public String myReader(){ 
     boolean isExit = true; 
     while (isExit){ 
      System.out.print("$"); 
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 

      try { 
       String readLine = br.readLine(); 
       if (readLine != null && readLine.trim().length() > 0){ 
        if (readLine.equalsIgnoreCase("showlist")){ 
         System.out.println("List 1"); 
         System.out.println("List 2"); 
         System.out.println("List 3"); 
        } if (readLine.equalsIgnoreCase("shownewlist")){ 
         System.out.println("New List 1"); 
         System.out.println("New List 2"); 
        } if (readLine.equalsIgnoreCase("exit")){ 
         isExit = false; 
        } 
       } else { 
        System.out.println("Please enter proper instrictions"); 
       } 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

     } 
     return "Finished"; 
    } 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 
     System.out.println("Please Enter inputs for the questions asked"); 
     TestInput ti = new TestInput(); 
     String reader = ti.myReader(); 
     System.out.println(reader); 
    } 

에 대한 샘플 코드 것은 출력됩니다.