Skip to content
Snippets Groups Projects
Commit 6d3fbc80 authored by Iina Siekkinen's avatar Iina Siekkinen
Browse files

Korjattu tehtävä

parent d7be1945
No related branches found
No related tags found
No related merge requests found
Pipeline #76130 passed
package fi.utu.tech.ooj.exercise1.teht2;
import java.util.ArrayList;
import java.util.List;
class NegativeArrayValuesException extends Exception {
private List<Integer> invalidIndices;
private List<Integer> invalidValues;
public NegativeArrayValuesException(List<Integer> indices, List<Integer> values) {
this.invalidIndices = indices;
this.invalidValues = values;
}
public List<Integer> getInvalidIndices() {
return invalidIndices;
}
public List<Integer> getInvalidValues() {
return invalidValues;
}
}
public class Calculator {
public static float avg(int[] nums) throws EmptyArrayException {
public static float avg(int[] nums) throws EmptyArrayException, NegativeArrayValuesException {
int sum = 0;
if (nums == null || nums.length == 0)
if (nums == null || nums.length == 0) {
throw new EmptyArrayException();
for(int n: nums) sum += n;
return sum / nums.length;
}
List<Integer> invalidIndices = new ArrayList<>();
List<Integer> invalidValues = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
if (nums[i] < 0) {
invalidIndices.add(i + 1);
invalidValues.add(nums[i]);
} else {
sum += nums[i];
}
}
if (!invalidIndices.isEmpty()) {
throw new NegativeArrayValuesException(invalidIndices, invalidValues);
}
// Palautetaan keskiarvo
return (float) sum / nums.length;
}
}
\ No newline at end of file
......@@ -2,19 +2,22 @@ package fi.utu.tech.ooj.exercise1.teht2;
public class Teht1 {
public static void SuoritaTeht1() {
//Tulostetaan info-rivi, jotta suoritusta on helpompi seurata
System.out.println("Suoritetaan Tehtävä 1");
int[] nums = new int[] { };
int[] nums = new int[] {1, -2, -3, 4};
Float result = -1f;
try {
result = Calculator.avg(nums);
System.out.println(result);
} catch (EmptyArrayException e) {
System.out.println("Oho, tapahtui hassuja. Taulukko on tyhjä.");
} catch (NegativeArrayValuesException e) {
for (int i = 0; i < e.getInvalidIndices().size(); i++) {
System.out.println("Antamasi taulukon " + e.getInvalidIndices().get(i) + ". luku " + e.getInvalidValues().get(i) + " on virheellinen");
}
catch(EmptyArrayException e) {
System.out.println("Oho, tapahtui hassuja");
}
//Tulostetaan info-rivi, jotta suoritusta on helpompi seurata
System.out.println("Tehtävä 1 suoritus päättyi");
}
}
\ 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