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

Write a java program that reads a sequence of integers into an ArrayList and the

ID: 3806427 • Letter: W

Question

Write a java program that reads a sequence of integers into an ArrayList and then computes the alternating sum of all elements. For example, if the program is executed with the input data


1 4 9 16 9 7 4 9 11


Then it computes


1-4+9-16+9-7+4-9+11 = -2.
Your program needs to continue accepting integers until user enters “done”. Then, the program displays the alternating sum of all elements.


A sample run is given below.


Please enter value or enter done: 1
Please enter value or enter done: 4
Please enter value or enter done: 9
Please enter value or enter done: 16
Please enter value or enter done: 9
Please enter value or enter done: 7
Please enter value or enter done: 4
Please enter value or enter done: 9
Please enter value or enter done: 11
Please enter value or enter done: done
The alternating sum of all elements is: -2

Explanation / Answer

import java.util.Scanner;

public class chegg_sum {

public static void main(String[] args) {
/* Enter your code here. Print output to STDOUT. Your class should be named Solution. */
int sum=0,temp,count=1;
System.out.println("Please enter value or enter done:");
Scanner scanner = new Scanner(System.in);
String choice = scanner.nextLine();
   while(!choice.equals("done"))
   {
       temp=Integer.parseInt(choice);
       if(count%2==0)
       {
           sum=sum-temp;
       }
       else
       {
           sum=sum+temp;
       }
       count=count+1;
       System.out.println("Please enter value or enter done:");
choice=scanner.nextLine();
   }
   System.out.println("The alternating sum of all elements is:" + sum);
}
}

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