Java – finds the sum of numbers in the array – excluding the number 13 and the number after it
I want to write a program in Java, give an array and find the sum of all the numbers in the array - with one exception! Since the number 13 is very unlucky, I suggest that we exclude the number 13 completely and the number directly after 13 (if any) from the sum
This program, which I will call sum13, should produce the following results from the following inputs (these are just a few examples):
Sum13 ([1,2,1]) = 6 this is normal; No 13 is here
Sum13 ([5,13,2]) = numbers after 5, 13 and 13 are excluded
Sum13 ([13,13]) = 0 array contains only 13, so they are not included
Sum13 ([1,1,13]) = 4 a slightly longer expected output example
This is the code I proposed for sum13:
public int sum13(int[] nums) { int sum = 0; for (int i = 0; i < nums.length; i++) { // we start by adding all the non-13s to the sum if (nums[i] != 13) sum += nums[i]; } // Now we go back and remove all the non-13s directly after a 13 for (int j = 0; j < nums.length; j++) { // the outermost loop checks if the numbers are a 13 if (nums[j] == 13 && j < nums.length - 1) { for (int k = j + 1; k < nums.length; k++) { // this loop checks that the number after the 13 is not a 13 if (nums[k] != 13) { sum -= nums[k]; break; } } } } return sum; }
The above program is effective, although it looks really chaotic!
Is there a better way to write such a program without multiple loops and nested IFS?
Solution
Well, you use I as an iterator When the current number is 13, just me In this way, not only do you not add 13 to the sum, but you also skip the next value
public int sum13(int[] nums) { int sum = 0; for (int i = 0; i < nums.length; i++) { // we start by adding all the non-13s to the sum if (nums[i] != 13){ sum += nums[i]; } else { i++; } } return sum; }