R Aji
R Aji

Reputation: 11

Need to split character numbers with comma and space using Java

Hi I am relatively new to Java. I have to compare amount value AED 555,439,972 /yr is lesser to another amount. so I tried to split using the code first

public static void main(String[] args) {
    String value= "AED 555,439,972 /yr";
    String[] tokens = value.split("\b");
    int[] numbers = new int[tokens.length];
    for (int i = 0; i < tokens.length; i++) {
        numbers[i] = Integer.parseInt(tokens[i]);
    }
    System.out.println(numbers);

}

but I am getting Exception in thread "main" java.lang.NumberFormatException: For input string: "AED 555,439,972 /yr".

Appreciate if someone can help me to solve the problem.

Upvotes: 0

Views: 217

Answers (4)

Naveed S
Naveed S

Reputation: 5236

Hope that you need to get the numeric value from the string.

First, use the following to remove all non-digit characters.

value.replaceAll("\\D", "")

\\D stands for non-digit character. Once every such character is replaced with empty string (which means those are removed), use Integer.parseInt on it. (Use Long.parseLong if the values can be out of Integer's range.)

In your code, you are trying to split the string by word character ends (which too is not done correctly; you need to escape it as \\b). That would give you an array having the result of the string split at each word end (after the AED, after the space following AED, after the first 3 digits, after the first comma and so on..), after which you are converting each of the resulting array components into integers, which would fail at the AED.

In short, the following is what you want:

Integer.parseInt(value.replaceAll("\\D", ""));

Upvotes: 1

Bohemian
Bohemian

Reputation: 424993

You are going about it the wrong way. It's a single formatted number, so treat it that way.

Remove all non-digit characters, then parse as an integer:

int amount = Integer.parseInt(value.replaceAll("\\D", ""));

Then you'll have the number of dirhams per year, which you can compare to other values.

Upvotes: 0

R Aji
R Aji

Reputation: 11

I found a solution from stack overflow itself

    public static void main(String[] args) {
    String line = "AED 555,439,972 /yr";
    String digits = line.replaceAll("[^0-9]", "");
    System.out.println(digits);
    } 

the output is 555439972

Upvotes: 0

StvnBrkdll
StvnBrkdll

Reputation: 4044

There are a few of things wrong with your code:

String[] tokens = value.split("\b");

The "\" needs to be escape, like this:

String[] tokens = value.split("\\b");

This will split your input on word boundaries. Only some of the elements in the tokens array will be valid numbers, the others will result in a NumberFormatException. More specifically, at index 2 you'll have "555", at index 4 you'll have 439, and at index 6 you'll have 972. These can be parsed to integers, the others cannot.

Upvotes: 0

Related Questions