2014-06-16 2 views
0

변수가 숫자와 다른지 (예 : char 또는 String) 확인해야합니다. if 문에 무엇을 넣어야합니까? x와 y 대신하는 경우 - 다른 사람의 경우,이 작업을 수행 할 어떤 콘솔wheather 변수가 숫자가 아닌지 확인하는 방법은 무엇입니까? Java

x = Integer.parseInt(Terminal.readLine()); 
y = Integer.parseInt(Terminal.readLine()); 

if() { 
    bombInput = false; 
    Terminal.printLine("Wrong input. Try again"); 
} else { 
    bombInput = true; 
} 
+2

그럼 당신은 이미에 시도했습니다 입력을 숫자로 변환하십시오 - 예외가없는'if' 문까지 가면 구문 분석 할 수 있습니다 ... –

+0

'Integer.parseInt' will thr 입력이 유효한 기계 형식의 'int'가 아니면 [[NumberFormatException'] (http://docs.oracle.com/javase/7/docs/api/java/lang/NumberFormatException.html)을 참조하십시오. 실제 사람의 의견을 듣고 싶다면 ['java.text.DecimalFormat'] (http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat)을 살펴 봐야합니다. html) 실제 사람들은 쉼표 나 점을 사용하여 숫자를 구분하는 경향이 있기 때문입니다. –

답변

2
try { 
    x = Integer.parseInt(Terminal.readLine()); 
    //it's an int 
} catch(NumberFormatException e) { 
    //not an integer 
} 

그러나 당신은 또한, 유틸리티 함수를 만들 수 있습니다 다음

public static boolean isInteger(final String s) { 
    try { 
     Integer.parseInt(s); 
     return true; 
    } catch(NumberFormatException e) { 
     return false; 
    } 
} 

과 :

String xAsString = Terminal.readLine(); 
if(isInteger(xAsString)){ 
    x = Integer.parseInt(xAsString); 
} else { 
    // :(
} 
1

에서 읽습니다 : 그들이 잘못된 입력을 제공하는 경우

try { 
    x = Integer.parseInt(Terminal.readLine()); 
    y = Integer.parseInt(Terminal.readLine()); 
    bombInput = true; 
} 
catch (NumberFormatException e) { 
    bombInput = false; 
    Terminal.printLine("Wrong input. Try again"); 
} 

Integer.parseInt 통화가 NumberFormatException 발생합니다. 오버 헤드가 너무 많이하지 않은 경우

0
String x = Terminal.readLine(); 
if (x != null) { 
    //use regex 
    if (x.matches("\\d")) { 
     //input is a number 
     //parse the input 
    } else { 
     //input is not a number 

    } 
} 
+0

음 ... 입력 문자열이 한 자리 긴 경우에만 작동합니다. '\\ d '다음에'+'를 추가하십시오. 또한 음수와 더하기 기호 (''+ '')로 시작하는 숫자가 허용되는지 여부를 알아야합니다. – ajb

+0

답변을 좀 더 자세히 설명해 주시겠습니까? – Qix

관련 문제