Skip to content
Snippets Groups Projects
Commit 29242010 authored by Hanna Kedonpää's avatar Hanna Kedonpää
Browse files

Add new file

parent cff87b48
Branches
No related tags found
No related merge requests found
a) What is the value of the variable result at the end of the program when the variable nums refers to the array [1, 2] accepted by the routine avg?
--> Muuttujan "result" arvo on lopussa 1.0, koska taulukon lukujen summa on 3 ja taulukon pituus 2 ja jakolaskun tulos typistetään kokonaisluvuksi.
b) What about when the array is empty? Why?
--> Kun taulukko on tyhjä, ohjelma heittää poikkeuksen EmptyArray ja muuttujan "result" arvo jää alustamattomaksi.
c) Modify the routine avg so that it only accepts arrays composed of non-negative numbers (x >= 0). If the array contains negative numbers, the routine should inform the client of all the indices where there are negative numbers in the array. The routine avg only informs the client, it does not print anything itself. Using this information, the client could do various things, but here wants to print a message "The X-th number Y in your array is invalid" for each case of a negative number. Here X would be the array index (starting from value 1) and Y the value at that index.
class EmptyArray extends Exception {}
float avg(int[] nums) throws EmptyArray {
int sum = 0;
if (nums == null || nums.length == 0)
throw new EmptyArray();
for (int n : nums) sum += n;
return (float) sum / nums.length;
}
// Tunnistaa negatiiviset numerot ja palauttaa listan niiden indekseistä.
List<Integer> findNegativeNumbers(int[] nums) {
List<Integer> invalidNumbers = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
if (nums[i] < 0) {
invalidNumbers.add(i);
}
}
return invalidINumbers;
}
void main() {
int[] nums = new int[] { 1, -2, -3, 4 };
Float result = null;
// Määrittelee järjestysluvulle oikean päätteen.
static String getSuffix(int value) {
int lastDigit = value % 10;
if (lastDigit == 1 && value % 100 != 11) {
return "st";
} else if (lastDigit == 2 && value % 100 != 12) {
return "nd";
} else if (lastDigit == 3 && value % 100 != 13) {
return "rd";
} else {
return "th";
}
}
List<Integer> invalidNumbers = findNegativeNumbers(nums);
if (!invalidNumbers.isEmpty()) {
for (int index : invalidNumbers) {
int x = index + 1;
int y = nums[index];
System.out.printf("The %d-th number %d in your array is invalid%n", x, y);
}
} else {
try {
result = avg(nums);
} catch (EmptyArray e) {
}
if (result != null) {
System.out.println(result);
}
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment