Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hi, this is a Java question. Thank you! Write a method that takes 2 arrays, A an

ID: 3696158 • Letter: H

Question

Hi, this is a Java question. Thank you!

Write a method that takes 2 arrays, A and B, of 10 integers as arguments. It also takes a boolean argument, flag. The function should find the sum of the elements of the arrays. If the flag is true, the function returns the smaller of the 2 sums. If the flag is false, it should return the larger of the 2 sums.

Below, I will start the method.

static int largerOrSmallerSum(int [] A, int [] B, boolean flag)   { …      }

My solution is here:

1 public class Review13
2 {
3 public static int largerOrSmallerSum(int[] A,int[] B, boolean flag )//return type required here
4 {
5 int sumOfA=0;
6 int sumOfB=0;
7 int large=0;
8 int small=0;
9 for(int i=0;i<A.length;i++)
10 sumOfA=sumOfA+A[i];
11 for(int j=0;j<B.length;j++)
12 sumOfB=sumOfB+B[j];
13 if(sumOfA>sumOfB)
14 {
15 large=sumOfA;
16 small=sumOfB;
17 }
18 else
19 {
20 large=sumOfB;
21 small=sumOfA;
22 }
23
24 if (flag==true)
25 {
26 System.out.println("the small sum of the two array is: ");
27 return small;
28 }
29 else
30 {
31 System.out.println("the large sum of the two array is: ");
32 return large;
33 }
34 }
35
36 public static void main(String[] args)
37 {
38 int []A={2,3,4,5,6,7,8,9,10,11};
39 int []B={1,2,3,4,5,6,7,8,9,10};
40 boolean flag= true;
41 largerOrSmallerSum(A,B,flag);
42 System.out.println(largerOrSmallerSum(A,B,flag));
43
44
45
46 }
47
48 }

The problem is, the sentence "the large sum of the two array is: " will be printed twice.

Why will happened?

How can I solve it?

please provide full code. thanks

Explanation / Answer

1 public class Review13
2 {
3 public static int largerOrSmallerSum(int[] A,int[] B, boolean flag )//return type required here
4 {
5 int sumOfA=0;
6 int sumOfB=0;
7 int large=0;
8 int small=0;
9 for(int i=0;i<A.length;i++)
10 sumOfA=sumOfA+A[i];
11 for(int j=0;j<B.length;j++)
12 sumOfB=sumOfB+B[j];
13 if(sumOfA>sumOfB)
14 {
15 large=sumOfA;
16 small=sumOfB;
17 }
18 else
19 {
20 large=sumOfB;
21 small=sumOfA;
22 }
23
24 if (flag==true)
25 {
26 System.out.println("the small sum of the two array is: ");
27 return small;
28 }
29 else
30 {
31 System.out.println("the large sum of the two array is: ");
32 return large;
33 }
34 }
35
36 public static void main(String[] args)
37 {
38 int []A={2,3,4,5,6,7,8,9,10,11};
39 int []B={1,2,3,4,5,6,7,8,9,10};
40 boolean flag= true;

// your are calling largeOrSmallrSum twice
41 //largerOrSmallerSum(A,B,flag);
42 System.out.println(largerOrSmallerSum(A,B,flag));
43
44
45
46 }
47
48 }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote