Write a java program Calculationjava to read integer numbers

 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 

Solution

import java.io.*;
public class HelloWorld{

     public static void main(String []args){
         //declare required variables
       BufferedReader br = null;
       try {
           String sCurrentLine;
           int nos[]={};
           //open file for reading
           br = new BufferedReader(new FileReader(\"Calculation.txt\"));
           //loop through EOF
           while ((sCurrentLine = br.readLine()) != null) {
                //read each line and pslit based on spaces
               String token[]=sCurrentLine.split(\" \");
               //convert each token into int and assign into array
               nos=new int[token.length];
               for(int i=0;i<token.length;i++)
               {
                    nos[i]=Integer.parseInt(token[i]);
               }
           }
          
           //delcre total variables
           int total=nos[0];
           //loop through array and find sum/difference
           System.out.print(\"The sequence is \ \"+nos[0]);
           for(int i=1;i<nos.length;i++)
           {
                if(i%2==0)
                {
                    total+=nos[i];
                    System.out.print(\" + \");
                }
                else
                {
                    total-=nos[i];
                    System.out.print(\" - \");
                }
                System.out.print(nos[i]);
           }
           //display result
           System.out.println(\" = \"+total);
       } catch (IOException e) {
           e.printStackTrace();
       }
     }
}

 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 arra

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site