์ž๋ฐ”์—์„œ ์ˆซ์ž ํŒ๋ณ„ํ•˜๊ธฐ

 

Java์˜ ์ŠคํŠธ๋ง์ด ์ˆซ์ž(์ •์ˆ˜, int)์ธ์ง€ ํŒ๋‹จํ•˜๊ธฐ ์œ„ํ•œ ๋ฐฉ๋ฒ• ๋‘ ๊ฐ€์ง€๋ฅผ ์†Œ๊ฐœํ•ฉ๋‹ˆ๋‹ค

 

 

1) ์ŠคํŠธ๋ง์˜ ๊ฐ ๋ฌธ์ž๋ฅผ ํ•˜๋‚˜ํ•˜๋‚˜ ์ˆœํšŒํ•˜๋ฉด์„œ ascii ์ฝ”๋“œ ๊ฐ’์„ ๋น„๊ตํ•˜๋Š” ๋ฐฉ๋ฒ•

 

์ฒซ ๋ฒˆ์งธ๋กœ ์†Œ๊ฐœํ•ด๋“œ๋ฆด ๋ฐฉ๋ฒ•์€ ์ž…๋ ฅ๋ฐ›์€ ๋ฌธ์ž์—ด(์ŠคํŠธ๋ง)์˜ ๊ฐ ๋ฌธ์ž๊ฐ€ 0~9 ascii ์ฝ”๋“œ๊ฐ’ ์‚ฌ์ด์— ์žˆ๋Š” char์ธ์ง€๋ฅผ ํŒ๋ณ„ํ•˜๋Š” ๋ฐฉ๋ฒ•์ž…๋‹ˆ๋‹ค.

 

0~9์˜ ascii ์ฝ”๋“œ๊ฐ’์€ ์‹ญ์ง„์ˆ˜๋กœ 48~57 ์ž…๋‹ˆ๋‹ค.

 

๋”ฐ๋ผ์„œ String์„ char[]๋กœ ๋ณ€ํ™˜ํ•œ ๋‹ค์Œ loop๋ฅผ ๋Œ๋ฉด์„œ ๊ฐ char๊ฐ€ 48~57์‚ฌ์ด์˜ ๊ฐ’์ธ์ง€๋ฅผ ํŒ๋‹จํ•˜์—ฌ ์ˆซ์ž์ธ์ง€๋ฅผ ํŒ๋ณ„ํ•ฉ๋‹ˆ๋‹ค.

 

์ฝ”๋“œ๋Š” ์•„๋ž˜์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค.

String str = "not a number";

boolean isNumber = true;

for(char c : str.toCharArray()) {

  if(c >= 48 && c<= 57) {
        continue;
  } else {
        isNumber = false;
        break;
  }
}
System.out.println("Is string a number ? answer: " + isNumber);

 

2) Integer.parseInt ๋ฅผ ์ด์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•

 

๋‘ ๋ฒˆ์งธ ๋ฐฉ๋ฒ•์€ Integer.parseInt ๋ฉ”์„œ๋“œ๋ฅผ ์ด์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•์ž…๋‹ˆ๋‹ค.

 

parseInt ๋ฉ”์„œ๋“œ์— ๋Œ€ํ•œ javadoc ๋ฌธ์„œ์—๋Š” ์•„๋ž˜์™€ ๊ฐ™์ด ์„ค๋ช…์ด ๋‚˜์™€์žˆ์Šต๋‹ˆ๋‹ค.

public static int parseInt(String s)
                    throws NumberFormatException
Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to theparseInt(java.lang.String, int) method.

 

Parameters:
s - a String containing the int representation to be parsed
Returns:
the integer value represented by the argument in decimal.
Throws:
NumberFormatException - if the string does not contain a parsable integer.

 

 

์ฆ‰, ๋ฌธ์ž๋กœ ํ‘œํ˜„๋œ ์ˆซ์ž๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ int๋กœ returnํ•˜๋Š”๋ฐ์š”

์ž…๋ ฅ๋ฐ›์€ ์ŠคํŠธ๋ง์ด ์ˆซ์ž๊ฐ€ ์•„๋‹ ๊ฒฝ์šฐ NumberFormatException์˜ˆ์™ธ๋ฅผ ๋ฐœ์ƒ์‹œํ‚ต๋‹ˆ๋‹ค.

 

๋”ฐ๋ผ์„œ ์œ„ ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ NumberFormatException์˜ ๋ฐœ์ƒ ์—ฌ๋ถ€์— ๋”ฐ๋ผ ํ•ด๋‹น ์ŠคํŠธ๋ง์ด ์ˆซ์ž์ธ์ง€ ์•„๋‹Œ์ง€๋ฅผ ํŒ๋ณ„ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

์ด ๋ฐฉ์‹์„ ์‚ฌ์šฉํ•œ ์ฝ”๋“œ๋Š” ์•„๋ž˜์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค.

 

String str = "421303";

boolean isNumber = false;

try {

Integer.parseInt(str);

isNumber = true;

} catch (NumberFormatException e) {

// do nothing

}

System.out.println("Is string a number ? answer: " + isNumber);

 

Integer ๋ฟ๋งŒ ์•„๋‹ˆ๋ผ ๋‹ค๋ฅธ wrapper ํด๋ž˜์Šค๋“ค์—๋„ Long.parseLong, Double.parseDouble ๋ฉ”์„œ๋“œ๋“ค์ด ์žˆ์œผ๋‹ˆ ์ฐธ๊ณ ํ•˜์‹œ๊ธฐ ๋ฐ”๋ž๋‹ˆ๋‹ค.

 

 

์œ„ ๋‘ ๊ฐ€์ง€ ๋ฐฉ๋ฒ• ์™ธ์— ๋˜ ์ข‹์€ ๋ฐฉ๋ฒ•์ด ์žˆ์œผ์‹  ๋ถ„๋“ค ์ œ๋ณด๋ฐ›์Šต๋‹ˆ๋‹ค ใ…Ž

 

๋‚ด์šฉ์ด ๋„์›€์ด ๋˜์…จ๋‹ค๋ฉด ๊ณต๊ฐ ๊พน ๋ˆ„๋ฅด๊ณ  ๊ฐ€์ฃผ์„ธ์š”~