2017-11-25 53 views
1

저는 제가 작성한 은행 관리 프로그램에 연결하는 보조 프로그램을 만들고 있습니다. 사용자가 명령 필드에 입력 할 수 있도록하려면 $ 5를 추가하거나 $ 10500 또는 다른 금액을 추가하십시오. 어떻게하면 "추가 $"를 무시하면서 "10500"을 계산할 수 있습니다. "add $"는 사용자가 작업을 수행하기 위해 입력하는 명령을 확인하는 데 사용됩니다. 이것은 내가 지금까지 가지고있는 것이다.정수 앞에 필요한 텍스트 문자열을 무시하면서 텍스트 필드의 정수 값을 계산하고 싶습니까?

} else if (AssistantFrame.getCommand().equalsIgnoreCase("add $5")) { 

     BankBalance.addToBalance(5); 

} 

이것은 잔액에 돈을 추가하는 코드입니다. 그런

public static void addToBalance(int balanceAdd){ 

    Commands.setContinuity(0); 

    if(fileBalance.exists()) { 

      try { 
       loadBalance(); 
      } catch (FileNotFoundException | UnsupportedEncodingException e) { 

      } 

      balance += balanceAdd; 

      try { 
       saveBalance(); 
      } catch (FileNotFoundException | UnsupportedEncodingException e) { 

      } 

      AssistantFrame.updateAssistant("Your balance has been succesfully updated.\nYour new balance is - $" + balance); 

    } else { 

     AssistantFrame.updateAssistant("Sorry, but you don't seem to have a personal\nbank balance created yet."); 

    } 
+0

의 JFormattedTextField 아마도 –

답변

2

뭔가 :

String command = AssistantFrame.getCommand(); 
int amount = Integer.parseInt(command.replaceAll("[^\\d]","")); 
BankBalance.addToBalance(amount); 
0

는 내가 모든 문자를 반복한다 할 것이다, 그 값이 48과 57 사이에 포함 있는지 확인하고, 문제가 계속된다면 추가 그것들을 String으로 변환합니다. 숫자 만 포함 된 문자열을 갖게됩니다. 당신은 단지 '있는 Integer.parseInt (...)'

0

당신 사용 String.startsWith(String)를 사용하여 문자열을 구문 분석하고 분석하기 전에 다음 String.substring(int)를 사용할 수 있습니다. 마찬가지로,

String command = "add $10"; 
if (command.startsWith("add $")) { 
    int v = Integer.parseInt(command.substring(5)); 
    System.out.println(v); 
} 

어느 명령을 구문 분석 달성하기 위해 노력하고 무엇

10 
0

출력합니다. 명령이 충분히 단순하면 다음 예제를 간단하게 수행 할 수 있습니다 :

if(command.startsWith("add $")){ 
    money=command.substring(5); 
    todo=ADD; 
else if(command.startsWith("something else")){ 
    ... 
    todo=SOMETHING_ELSE; 
} 
... 

또는 명령이 좀 더 복잡해지면 어휘 분석기 코드로 이동하십시오.

... 어휘 분석, 렉싱 또는 토큰 화는 문자 시퀀스 (컴퓨터 프로그램이나 웹 페이지와 같은)를 토큰 시퀀스 (할당되고 식별 된 의미가있는 문자열)로 변환하는 프로세스입니다. ... 예를의 Wikipedia

하나는 : here