-
Notifications
You must be signed in to change notification settings - Fork 1.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
implemented getStatistic() method #1626
base: master
Are you sure you want to change the base?
Changes from 5 commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,43 @@ | ||
package core.basesyntax; | ||
|
||
import java.io.BufferedReader; | ||
import java.io.BufferedWriter; | ||
import java.io.FileReader; | ||
import java.io.FileWriter; | ||
import java.io.IOException; | ||
|
||
public class WorkWithFile { | ||
public void getStatistic(String fromFileName, String toFileName) { | ||
int supply = 0; | ||
int buy = 0; | ||
|
||
try (BufferedReader reader = new BufferedReader(new FileReader(fromFileName))) { | ||
String line; | ||
while ((line = reader.readLine()) != null) { | ||
String[] parts = line.split(","); | ||
String operation = parts[0].trim(); | ||
int amount = Integer.parseInt(parts[1].trim()); | ||
|
||
if ("supply".equalsIgnoreCase(operation)) { | ||
supply += amount; | ||
} else if ("buy".equalsIgnoreCase(operation)) { | ||
buy += amount; | ||
} | ||
} | ||
} catch (IOException e) { | ||
throw new RuntimeException(e); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Using |
||
} | ||
writeToFile(supply, buy, toFileName); | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The |
||
|
||
public void writeToFile(int supply, int buy, String toFileName) { | ||
int result = supply - buy; | ||
try (BufferedWriter writer = new BufferedWriter(new FileWriter(toFileName))) { | ||
writer.write("supply," + supply + "\n"); | ||
writer.write("buy," + buy + "\n"); | ||
writer.write("result," + result + "\n"); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The string "result" is hardcoded. Consider declaring it as a constant to enhance readability and maintainability. |
||
} catch (IOException e) { | ||
throw new RuntimeException(e); | ||
} | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The strings "supply" and "buy" are hardcoded. Consider declaring them as constants to enhance readability and maintainability.