2017-03-05 3 views
-1

Integer.parseInt()를 사용하여 phonenumber를 나타내는 문자열을 사용할 수있는 int로 변환하려고합니다.() 나는 그냥있는 Integer.parseInt를 사용하여 작동하는 하드 코딩 된 문자열을 대체하려고 할 때 그래서int로 변환 할 때 Java 문자열 생성 오류가 발생했습니다.

import java.util.*; 
import java.lang.Integer; 

public class TelephoneNumberValidator { 
    public static void main(String[] args) { 
     final String VALID_PHONE_PATTERN = "[0-9]{3}[-| ]?[0-9]{3}[-| ]?[0-9]{4}"; 
     final int NUMBERS_FOLLOWING_AREA_CODE = 7; 
     final int DECRYPTED_AREA_CODE = 212; 
     Scanner scanKeyboard = new Scanner(System.in); 
     String userInput; 

     do { 
      System.out.println("Enter a 10-digit telephone number with optional space or dash after the first and the second block of three digits >"); 
      userInput = scanKeyboard.nextLine(); 
      //check to see if the phone number is correct 
      if (!userInput.matches(VALID_PHONE_PATTERN)) 
      { 
       System.out.println("The given input \" " + userInput + " \" is not valid"); 
      } 
     }while (!userInput.matches(VALID_PHONE_PATTERN)); 

     //extract int from string 
     String phoneJustNumbers = userInput; 
     phoneJustNumbers = phoneJustNumbers.replaceAll("-",""); // replaces hyphens 
     phoneJustNumbers = phoneJustNumbers.replaceAll(" ", ""); 

     System.out.println("Processing encrypted number \"" + phoneJustNumbers + "\""); 
     //check the first 3 digits (aka area code) to see if it matches 212 
     int areaCode = Integer.parseInt(phoneJustNumbers);//gets area code 
     int placeholderForAreaCode = 111; //set 111 so that each number in area code can be accounted for 
     int placeholderForEntirePhoneNum = 1111111111; //set each digit to 1 so we can shift later 
     for (int j = 0; j <= 9; j++) 
     { 
      if ((areaCode + (placeholderForAreaCode * j) == DECRYPTED_AREA_CODE)) // we are shifting each digit by one 
                         // to see if it matches the decrypted area code 
      { 
       System.out.println("The telephone number is \"" + (Integer.parseInt(phoneJustNumbers) * placeholderForEntirePhoneNum * j) 
         + "\" with a shift value of " + j); 
      } 
      else 
      { 
       System.out.println("The telephone number \"" + userInput + "\" cannot be decrypted area code."); 
      } 
     } 

    } 
} 

: 이것은 내 코드입니다

Enter a 10-digit telephone number with optional space or dash after the first and the second block of three digits > 
5558759142 
Processing encrypted number "5558759142" 
Exception in thread "main" java.lang.NumberFormatException: For input string: "5558759142" 
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) 
    at java.lang.Integer.parseInt(Integer.java:583) 
    at java.lang.Integer.parseInt(Integer.java:615) 
    at TelephoneNumberValidator.main(TelephoneNumberValidator.java:32) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:498) 
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) 

Process finished with exit code 1 

:

내가지고있어 오류입니다 . 이것은 내가 어떻게하면 내 끈을 깨끗하게하는 방법이이 일을 멈추게한다고 믿게한다. 나는 자바에 익숙하지 않아서 내가 왜 그런 짓을했는지, 내가 잘못했는지 모른다.

답변

0

가장 큰 값인 int은 2,147,483,647이 될 수 있습니다. (Integer.MAX_VALUE를보십시오.) 귀하의 전화 번호는 그보다 훨씬 큽니다. long의 최대 값은 9,223,372,036854775807이므로 Long.parseLong()을 대신 사용해보십시오.

+0

예. 이것이 문제였습니다. 고마워요! –

0

범위를 벗어났습니다. int에 간단하게 맞을 수있는 최대 숫자는 숫자가 나타내는 50 억 개의 값에 맞지 않습니다.

대신 길게 시도하십시오.

또는 더 나은 방법은 전화 번호를 나타내는 데 사용하는 특정 클래스를 사용하는 것입니다. 예를 들어 해당 숫자의 숫자 만 포함 된 배열을 사용하고 사용자가받은 전체 초기 문자열을 유지하는 등의 작업도 가능합니다.

사실 : 전화 번호에 숫자가 포함되어 있다는 사실이 전화 번호를 실제 숫자로 저장해야한다는 것을 의미하지 않습니다.

+0

예. 고마워요! –

+0

그런 다음 앞으로 나아가서 도움이되는 것으로 생각하는 대답을 수락하십시오. – GhostCat

0

입력이 Integer가 수용 (저장) 할 수있는 최대 값을 초과합니다. 이 문제를 극복하려면 데이터 유형을 long으로 변경하십시오.

정수 연산이 너무 많습니다. 전화 클래스를 만들고 접두사 등을 별도의 필드/특성으로 만든 다음 해당 필드에 대한 작업을 수행 할 수 있습니다. 어쩌면 문자열의 사용법은 수학적 연산을 할 필요가 없다면 더 좋을 것입니다. 변환은 바람직하지 않습니다.