Skip to content
Snippets Groups Projects
Commit 22c38737 authored by Dao's avatar Dao
Browse files

feat(part2): Exercise 1.

parent 266ff63c
No related branches found
No related tags found
No related merge requests found
### IntelliJ IDEA ###
/.idea/
out/
!**/src/main/**/out/
!**/src/test/**/out/
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
import java.util.ArrayList;
public class Exercise1 {
class EmptyArray extends Exception {
}
class ArrayNegativeNumbersException extends Exception {
public ArrayNegativeNumbersException(String message) {
super(message);
}
}
public void main() {
printAvg(new int[]{1, -2, -3, 4});
printAvg(new int[]{1, 2, 3});
printAvg(new int[]{-1, 2, 3, -4});
}
public float avg(int[] nums) throws EmptyArray, ArrayNegativeNumbersException { // 1
int sum = 0;
ArrayList<String> errors = new ArrayList<String>();
if (nums == null || nums.length == 0)
throw new EmptyArray(); // 2
for (int i = 0; i < nums.length; i++) {
int n = nums[i];
if (n < 0) {
errors.add(getErrorMessage(i, n));
} else {
sum += n;
}
}
if (!errors.isEmpty()) {
throw new ArrayNegativeNumbersException(String.join("\n", errors));
}
return sum / nums.length;
}
private void printAvg(int[] nums) {
Float result;
try {
result = avg(nums);
System.out.println(result);
} // 3
catch (EmptyArray e) {
} // 3
catch (ArrayNegativeNumbersException e) {
System.out.println(e.getMessage());
}
}
private String getErrorMessage(int index, int number) {
int position = index + 1;
String positionSuffix = switch (position) {
case 1 -> "st";
case 2 -> "nd";
case 3 -> "rd";
default -> "th";
};
return String.format(
"The %d%s number %d in your array is invalid",
position,
positionSuffix,
number
);
}
}
public class Main {
public static void main(String[] args) {
Exercise1 exercise = new Exercise1();
exercise.main();
}
}
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment