In: Computer Science
(JAVA)
ExceptionSum
The objective of this exercise is to create a method that adds all the numbers within an array with an exception you cant sum the 6, and the 7, and the numbers between them cannot be added too, taking into account that whenever a 6 appears will be followed by a 7.
If we have an array such that [1,2,3,6,10,9,8,7,5] when we pass it through the method it will give us an int such that the sum will be 11.
In order to do this exercise, you will have to make a static public method, called sum, this method will return int, which will be the sum of all the numbers in the array except the numbers between 6 and 7, and the same 6 and 7.
Here is the class diagram.
ExceptionSum
+ sum(int [] a) : int
CODE:
import java.util.*;
public class ExceptionSum
{
public static void main(String[] args)
{
Scanner scan = new
Scanner(System.in);
System.out.print("Enter Number of
elements : ");
int n=scan.nextInt();//taking
input
int[] a = new int[n];//array
declaration
int i=0;//loop variable
System.out.print("Enter elements :
");
//loop to get the elements from
user.
for(i=0;i<n;i++)
{
a[i] =
scan.nextInt();//taking input
}
System.out.print("The sum is :
");
System.out.print(sum(a));//printing
sum.
}
public static int sum(int[] a)
{
//varibles required and two
flags.
int sum_value =
0,flag_6=0,flag_7=0;
for(int
i=0;i<a.length;i++)
{
if(a[i] ==
6)
{
flag_6 = 1;//turning on flag
}
else if(a[i] ==
7)
{
flag_7 = 1;//turning on flag
}
//if there is no
6 and after 7 is encountered.
else if(flag_6
== flag_7)
{
sum_value += a[i];//adding the value to the
sum.
}
}
return sum_value;//returning sum
value
}
}
CODE ATTACHMENTS:
OUTPUT:
I have used flags here to get the exception.
The flags are equal before 6 is encountered and after 7 is encountered.
Please do comment for any queries.
Please like it.
Thank you.