2017-01-13 1 views
0

Scanner에서 입력을 차단할 수 있는지 여부를 어떻게 확인할 수 있습니까?루프에 내부에 스캐너에 내용이 있는지 확인하십시오.

다음 예를 고려하십시오. 각 루프 반복에서 사용자 입력이 있으면 입력을 받아 들여야하지만 입력이 없으면 입력없이 진행해야합니다. 대신 reader.nextLine()은 진행하기 전에 사용자가 줄을 입력 할 때까지 기다립니다.

public void creatureCombate() { 

    while (true) { 
     Scanner reader = new Scanner(System.in); 
     String userInput = reader.nextLine(); 

     wait(1); 
     System.out.println("Wolf attacks"); 

     if(userInput.equals("hit")){ 
      System.out.println("hit wolf"); 
     } else{ 
      System.out.println("Tries again"); 
     } 
    } 
} 
+0

그리고 당신의 질문은 ... –

+3

흠은 새로운 Scaner 개체를 만들 수 nessesary입니다 루프가 실행될 때마다? 그리고 @JoeC가 지적한대로, 왜 당신의 경우에 문제가됩니까? 위의 코드에서 문제가 보이지 않습니까? –

+0

친절하게도 문제에 대한 자세한 정보를 제공합니다. – Uzair

답변

0

모든 nextXxx()hasNextXxx() 방법이 차단되기 때문에,을 아니, 당신은 "아무것도 입력하지 않은 경우 입력없이 진행"하지 수 있습니다.

입력을 기다리는 동안 코드를 실행 (예 : 늑대 공격)하려면 여러 스레드가 필요합니다.

0

당신은 다중 스레드를 사용하고 input 하나 예를 들어, 완료 또는 시간 초과 될 때까지 main thread 대기를 할 필요가 :

public static void main(String[] args) throws Exception { 
    final List<String> input = new ArrayList<>(); 
    Scanner scanner = new Scanner(System.in); 
    int count = 0; 
    while (count < 10) { 
     Runnable inputThread =() -> { 
      scanner.reset(); 
      System.out.println("Enter input"); 
      try{ 
       String line = scanner.nextLine(); 
       input.add(line); 
      }catch(Exception e){} 
     }; 

     Thread t = new Thread(inputThread); 
     t.start(); 

     Thread.currentThread().join(10000); 
     t.interrupt(); 

     if(input.isEmpty()){ 
      System.out.println("Nothing enteresd"); 
     } else{ 
      System.out.println("Entered :" + input.get(0)); 
      input.clear(); 
     } 
     count++; 
    } 
    scanner.close(); 
} 
관련 문제