ArrayList-In-Class-E..

advertisement
In Class Exercise on ArrayList
(1) Write a program that reads a sequence of integers into an array and then computes the
alternating sum of all elements in the array. 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 repeatedly ask for more input from the user until the user is done
entering all the input and then display the alternating sum of all elements.
A sample run is given below. User input is shown in bold
java TestArrayList
Please enter a value : 1
Do you have more input to enter? Yes
Please enter a value : 4
Do you have more input to enter? Yes
Please enter a value : 9
Do you have more input to enter? Yes
Please enter a value : 16
Do you have more input to enter? Yes
Please enter a value : 9
Do you have more input to enter? Yes
Please enter a value : 7
Do you have more input to enter? Yes
Please enter a value : 4
Do you have more input to enter? Yes
Please enter a value : 9
Do you have more input to enter? Yes
Please enter a value : 11
Do you have more input to enter? No
The alternating sum of all elements is: -2
You may use the following solution from your previous Lab which uses Arrays.
/**
*Cecilia Ford and Ben Buckley
*September 3rd 2013
*Lab 2
*Java Review: arrays
*/
import java.util.Scanner;
public class TestArray {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int[] array = new int[Integer.parseInt(args[0])];//instance variable
for(int i = 0; i < array.length; i++){//user fills in array
System.out.println("Please enter value " + (i +1) + " :");
array[i] = keyboard.nextInt();
}
int sum = 0;
for(int i=0; i< array.length; i++){//alternates adding and subtracting
integers
if(i%2==0){
sum+= array[i];
}
else{
sum-= array[i];
}
}
//results
System.out.println("The alternating sum of all elements is: " + sum);
}
}
Download