Search code examples
javaintjtextfieldcalculation

I want to calculate the value of an integer in a text field while ignoring a string of text that is required before the integer?


I am making my own assistant program that connects to a bank management program i wrote. I want the user to be able to type into the command field: add $5 or add $10500 or any other amount. How would i calculate the "10500" while ignoring the "add $". The "add $" is used to check what command the user is typing to perform the action. This is what i have so far.

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

        BankBalance.addToBalance(5);

}

This is the code that handles adding the money to the balance.

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.");

    }

Solution

  • Something like that:

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