2012-11-25 4 views
0

저는 현재 사용자에게 질문을하고 정수 답변을 요구하는 간단한 기능 (아래에 게시 됨)이 있습니다.문자 유형별 콘솔 입력 제한

Java에 콘솔에 입력 할 수있는 문자를 제한하는 방법이 있습니까? 즉, 숫자 만 입력 할 수 있습니다.

다른 프로그래밍 언어에서이 작업을 수행하는 간단한 방법이 있지만 Java에서이 작업을 내 기능에 구현하려면 어떻게해야합니까?

static int questionAskInt(String question) 
{ 
    Scanner scan = new Scanner (System.in); 
    System.out.print (question+"\n"); 
    System.out.print ("Answer: "); 
    return scan.nextInt(); 
} 

답변

0

Scanner.hasNextInt를 사용하고는 integer 값을 통과 할 때까지 루프 동안, 당신은 입력을 제공 할 수있는 사용자를 제한 할 수 있습니다.

while (!scan.hasNextInt()) { 
    System.out.println("Please enter an integer answer"); 
    scan.next(); 
} 
return scan.nextInt(); 

또는, 그것은 카운트 변수를 사용하여, infinite loop로 전환되지 않도록 당신은 또한 (기회의 특정 번호를 제공 할 수 있습니다 : -

int count = 3; 

while (count > 0 && !scan.hasNextInt()) { 
    System.out.println("Please enter an integer answer"); 
    System.out.println("You have " + (count - 1) + "more chances left."); 
    count--; 
    scan.next(); 
} 

if (count > 0) { 
    return scan.nextInt(); 
} 

return -1; 
+0

현재 일부 문자를 입력하려고 후 int가 아니며 이것을 누르면 무한 루프에 빠지게됩니다. "정수 응답을 입력하십시오"라는 더 좋은 방법이 있습니까? –

+0

@ mr.user1065741 .. 내가 게시 한 두 번째 방법을 시도해보십시오 ... –

+0

@ mr.user1065741 .. Take the 두 번째 코드의 최신 편집 –