-1

I am currently experimenting with Strings in Java.

For example you have a string "1234 Hello 56789" and now you want to calculate the average of the max and min value, which is (1234/5678)/2 = 58023.

How do you do that?

I tried Integer.parseInt which gives me an error.

I tried replaceAll("[^0-9]", "") which does not get me the min and max and therefore the avg. It outputs 123456789 which I do not want.

I also tried replaceAll("[^0-9]", "").split("\\D+") which just gives me 1234 56789, but I don't know how to get the min and max.

kiribu
  • 1
  • 1
  • 6
    I would start by forgetting the min, max, average parts. Instead, focus on "how can I extract numbers from a string"? Once you've done that part, the rest is simple maths. You probably want to think about whether your string can contain non-integers, whether you want to permit thousands separators in numbers, etc. – Jon Skeet Jan 02 '20 at 17:04
  • @Jon Skeet, it's very difficult regarding to locale representation of non-integer values. How can we predict what is the number 1,0 vs 1.0; or 1_000 instead of 1.000 OR 1,000.00? Not so simple, isn't it? – zlakad Jan 02 '20 at 17:31
  • 1
    @zlakad: No, it's definitely not simple. But that's the sort of thing the OP should be asking themselves in terms of defining their requirements. – Jon Skeet Jan 02 '20 at 18:56

1 Answers1

3

I also tried replaceAll("[^0-9]", "").split("\\D+")

This is a good first step. It will give you an array of strings (String[]). It is probably a good idea to then convert this to an int[]. See Converting a String array into an int Array in java

Once you have an int[], you can calculate the max and the min by referring to Finding the max/min value in an array of primitives using Java

By the way, the average is not (1234/5678)/2. It is (1234 + 5678)/2

Michael
  • 41,989
  • 11
  • 82
  • 128