This commit is contained in:
@@ -489,63 +489,3 @@ public class Sum {
|
||||
```
|
||||
|
||||
This is it! The code is ready.
|
||||
|
||||
---
|
||||
|
||||
Below are some modifications to the code for deeper understanding of basic language constructions primarily data types. It is always advised to try completing them by yourself before reading the solution. Modifications progress in difficulty from easy to hard.
|
||||
|
||||
# SumDouble
|
||||
|
||||
- Input data is 64-bytes floating point numbers.
|
||||
- Class should be named `SumDouble`.
|
||||
|
||||
## Solution
|
||||
|
||||
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