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

genarl array and solv as a beginner no advnc codeing Write a java program Calcul

ID: 3935571 • Letter: G

Question

 genarl array and solv as a beginner  no advnc codeing  Write a java program Calculation.java to read integer numbers from file and store them in an array. Then compute the alternating sum of all elements in an array.  For example, if your program reads the input                 1 4 9 16 9 7 4 9 11         then it computes                 1 - 4 + 9 - 16 + 9 - 7 + 4 - 9 + 11 = 2                  Create an input file Calculation.txt with following content:         1 4 9 16 9 7 4 9 11          Write a program named Calculation.java to perform the described function.  Sample Output:   Sample 1:  The sequence is  1  - 4  + 9  - 16  + 9  - 7  + 4  - 9  + 11  = -2 The sum of sequence is -2  Sample 2:  The sequence is  1  - 1  + 1  - 1  + 1  - 1  + 1  - 1  + 1  - 1  = 0 The sum of sequence is 0  Sample 3:  The sequence is  10  - 5  + 2  - 6  + 8  - 7  + 3  = 5 The sum of sequence is 5 

Explanation / Answer

Calculation.java

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class Calculation {
   public static void main(String[] args) throws FileNotFoundException {
       String fileName = "Calculation.txt";
       File file = new File(fileName);
       if(file.exists()){
       Scanner scan1 = new Scanner(file);
       int count = 0;
       while(scan1.hasNext()){
           scan1.next();
           count++;
       }
       int a[] = new int[count];
       Scanner scan = new Scanner(file);
       count = 0;
       while(scan.hasNext()){
           a[count++] = Integer.parseInt(scan.next());
       }
       System.out.println("The sequence is ");
       int sum = 0;
       for(int i=0; i<a.length; i++){
           if(i % 2 != 0){
               sum = sum + a[i];
           System.out.print(a[i]+" + ");
           }
           else{
               if(i == a.length-1){
                   System.out.print(a[i]+" = ");
               }
               else{
               System.out.print(a[i]+" - ");
               }
               sum = sum - a[i];
           }
       }
       System.out.println(sum);
       System.out.println("The sum of sequence is "+sum);
       }
       else{
           System.out.println("File Does not exist");
       }
   }
}

Output:

The sequence is
1 - 4 + 9 - 16 + 9 - 7 + 4 - 9 + 11 = 2
The sum of sequence is 2

Calculation.txt