How do I get the numbers in a String and then calculate the average of them?

java program to calculate average of 3 numbers
java program to find average of n numbers
java program to calculate average of 5 numbers
java program to find average of two numbers
java calculate average of array
how to calculate average in java
calculate average using for loop in java
write a program to find the sum and average of three numbers in java

So I am currently experimenting with Streams and I try to calculate the average of the numbers in the String "589 Hello 56" in a stream. My approach is like this:

List <int[]> experiment = a.stream()
    .map(x -> x.replaceAll("[^0-9]", "").split("\\D+"))
    .map(x-> Arrays.asList(x).stream().mapToInt(Integer::parseInt).toArray())
    .collect(Collectors.toList());

So I first get a Stringarray with "589 56", because I split the String. But after that I try to convert everything to an Integerarray to get the average more easily and it doesn´t work, because the "589 56" converts to "58956". Does anyone have a better approach? Thanks in advance.

To calculate the average using stream, you need :

double average = Arrays.stream(a.split("\\D+")) // split with non degits ["589", "56"]
        .mapToInt(Integer::valueOf) // convert each string to integer [589, 56]
        .average()  // OptionalDouble
        .getAsDouble(); // double 322.5

Or if you are not sure that your string can contain any number, then you need to avoid this with :

.orElse(0);

or

.orElseThrow(() -> new IllegalArgumentException("no number in the string"));

instead of .getAsDouble();


Or if you want to go deeper and for example avoid cases where the numbers can be in front of any non digits for example a45 Hello 9a7 where the numbers can be a part of a word, in this case you can go with Pattern and Matcher with this regex \b\d+\b, which use work boundary, like so :

double average = Pattern.compile("\\b\\d+\\b")
        .matcher(a)
        .results()
        .map(MatchResult::group)
        .mapToInt(Integer::valueOf)
        .average()
        .orElse(0);

This last solution can work only from Java9+.

Java Program to Calculate average using Array, We will see two programs to find the average of numbers using array. of elements) and the numbers provided by user and finds the average of them using array. public class JavaExample { public static void main(String[] args) { double [] arr = {19, if you give %.4f then the output would have 4 digits * after decimal point. Average Definition. The free online Average Calculator will calculate the average of any group of numbers. Simply enter in as long of a string of numbers to average that you like into the box and separate the numbers by a comma and then press calculate to get the average of all of the numbers.

Try this one

String s = "589 Hello 56";
OptionalDouble average = Arrays.stream(s.split("\\D+"))
            .mapToInt(Integer::parseInt)// or maybe  .mapToDouble(Double::parseDouble)
            .average();

Calculate Average Values Based On A Specific String In In Your , I need to quickly calculate the average quarterly sales for a specific The criteria will be in the form of expression, number, cell reference or text string. If this argument is omitted ( as it is optional), then the Range is used. The average of a set of numbers is simply the sum of the numbers divided by the total number of values in the set. For example, suppose we want the average of 24 , 55 , 17 , 87 and 100 . Simply find the sum of the numbers: 24 + 55 + 17 + 87 + 100 = 283 and divide by 5 to get 56.6 .

The call to replaceAll strips all non-numeric characters from the string including the spaces. This converts '589 Hello 56' into '58956'. Try using replaceAll("[^0-9\\s]", "").

You will also need to split on the separator characters (i.e., the spaces) instead of the digits.

How to Get Average with Excel Formulas, How to calculate averages in Excel. Examples show how to average Excel cells with numbers, text, Match criterion in a string Cell A1 isn't included in the average, because it contains text, and the After you filter the rows in a list, you can use the SUBTOTAL function to average the visible rows. Get the numbers entered by the user Calculate the average of the numbers entered by the user Print the results with the whole number, a decimal, and two decimal positions The first method should take no arguments and return a String of numbers separated by spaces. The second method should take a String as its only argument and return a double

Java exercises: Calculate and print the average of five numbers , Scanner; public class Exercise12 { public static void main(String[] args) Input the number(n) you want to calculate the average: 4 Input number each other so it will be a problem to apply this code number like 37,25,59� I want to calculate the average value of several lists in python. These lists contain numbers as strings. Empty string isn't zero, it means a missing value. The best I could come up with is this. Is there a more elegant, succinct & efficient way of writing this?

Calculate sum of all numbers present in a string, A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles,� Go on clicking another column that you want to calculate the average, and then click Calculate > Average, see screenshot: 5 . After finishing the settings, please click Ok button, and the average of the total price has been calculated based on the same data in column A, see screenshot:

Find AVERAGE of a List in Python with Example, The average of a list can be done in many ways listed below: Pyt. The formula to calculate average is done by calculating the sum of the numbers in the list It is a straight forward way to calculate the average as you don't have to Learning Python Strings � Python String strip() � Python String count()� Write a C# Sharp program that takes four numbers as input to calculate and print the average. C# Sharp: Average of numbers. An average is the sum of a list of numbers divided by the number of numbers in the list. In mathematics and statistics, this would be called the arithmetic mean.

Comments
  • So you want to fetch all numbers from the string, then calculate the average of them?
  • The number gathering is a different operation...not sure why you would like to include it in any-stream-processing. Once you have those, you can stream the list and do whatever you want with them.
  • @ marstran Yes I want to fetch all the numbers. So in this case it would be "589" and "56". And than I want to calculate the average of these two which is (589+56)/2 = 322.5
  • Try this Arrays.stream(s.split("\\D+")) .mapToInt(Integer::parseInt) .average();
  • FYI: [^0-9] and \D is the same thing, so you first remove all non-digit characters, then try to split on the now non-existent non-digits, which means that split will do thing.
  • Well my IDEA sadly says: "Illegal escape character in string literal"
  • Thanks for the update but sadly my compiler says: Exception in thread "main" java.lang.NumberFormatException: For input string: "123456 789" when i try to convert it into an integerarray