Welcome! In this unit, we have an exciting and practical task that will test your Java programming skills. We will be parsing strings and making type conversions. So, let's dive into it!
Our task for the day involves creating a Java method called parseAndMultiplyNumbers()
. This method is designed to accept a string as an input. However, it's not just any string — the input we'll consider is a playful mix of numbers and words.
The purpose of this method is to analyze the input string, extract all the numbers, convert these numbers (currently string types) into integer data types, and then multiply all these numbers together. The final output? It's the product of all those numbers!
Here's an illustration for clarification. Given the input string "I have 2 apples and 5 oranges," our method should return the product of 2 and 5, which is 10.
The primary task is to parse the string and identify the numbers. To do that, let's create an empty string, num
, to accumulate digits and an ArrayList<Integer>
to collect all the numbers we find:
The next step requires iterating through the input string character by character. When we encounter a digit, we append it to our num
string. If a character isn’t a digit and isn’t empty, it means we've reached the end of a number.
