This commit is contained in:
@@ -503,4 +503,49 @@ Below are some modifications to the code for deeper understanding of basic langu
|
||||
|
||||
This modification is fairly easy. All we need to do is to replace all integers with floating point numbers.
|
||||
|
||||
> [!NOTE]
|
||||
> Here we can see all of the benefits of using `Character.isWhitespace()`, because if we had had for example a set of digits and check if the character is in that set we would need to add `.` (point) to that set to count floating point numbers as well.
|
||||
|
||||
So here's the updated code
|
||||
|
||||
```java
|
||||
// SumDouble.java
|
||||
|
||||
public class SumDouble {
|
||||
|
||||
public static void main(String[] args) {
|
||||
double sum = 0; // int -> double
|
||||
for (String argument : args) {
|
||||
StringBuilder number = new StringBuilder();
|
||||
for (char c : argument.toCharArray()) {
|
||||
if (!Character.isWhitespace(c)) {
|
||||
number.append(c);
|
||||
} else {
|
||||
if (!number.isEmpty()) {
|
||||
sum += Double.parseDouble(number.toString()); // Integer.parseInt -> Double.parseDouble())
|
||||
}
|
||||
number = new StringBuilder();
|
||||
}
|
||||
}
|
||||
|
||||
if (!number.isEmpty()) {
|
||||
sum += Double.parseDouble(number.toString()); // Integer.parseInt() -> Double.parseDouble()
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println(sum);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This code will work fine and pass all the tests, but can we improve it?
|
||||
|
||||
We can see repeating part of code here
|
||||
|
||||
```java
|
||||
if (!number.isEmpty()) {
|
||||
sum += Double.parseDouble(number.toString()); // Integer.parseInt() -> Double.parseDouble()
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
Reference in New Issue
Block a user