Write a program that reads integers , one per line, and displays their sum. Also
ID: 3546467 • Letter: W
Question
Write a program that reads integers , one per line, and displays their sum. Also, display all the numbers read, each with an annotation giving its percentage contribution to the sum. Use a method that takes the entire array as one argument and returns the sum of the numbers in the array. HINT: Ask the user for the number of integers to be entered, create an array of that length, and then fill the array with the integers read. A possible dialogue between the program and the user follows:
How many numbers will you enter?
4
Enter 4 integers,one per line:
2
1
1
2
the sum is 6.
the numbers are:
2, which is 33.3333% of the sum.
1, which is 16.6666% of the sum.
1, which is 16.6666% of the sum.
2, which is 33.3333% of the sum.
Explanation / Answer
import java.util.Scanner;
public class ArrayFun {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] numbers;
int sum = 0, len, n;
System.out.print("How many numbers will you enter? ");
len = Integer.parseInt(scanner.nextLine());
numbers = new int[len];
System.out.print("Enter " + Integer.toString(len) + " integers, one per line: ");
for(int i = 0; i < len; i++) {
n = Integer.parseInt(scanner.nextLine());
numbers[i] = n;
sum += n;
}
System.out.print("The sum is: " + sum + " The numbers are: ");
for(int num : numbers) {
System.out.println(Integer.toString(num) + ", which is " + (double)Math.round((double)num / (double)sum * 10000)/100 + "% of the sum.");
}
}
RAW Paste Data
import java.util.Scanner;
public class ArrayFun {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] numbers;
int sum = 0, len, n;
System.out.print("How many numbers will you enter? ");
len = Integer.parseInt(scanner.nextLine());
numbers = new int[len];
System.out.print("Enter " + Integer.toString(len) + " integers, one per line: ");
for(int i = 0; i < len; i++) {
n = Integer.parseInt(scanner.nextLine());
numbers[i] = n;
sum += n;
}
System.out.print("The sum is: " + sum + " The numbers are: ");
for(int num : numbers) {
System.out.println(Integer.toString(num) + ", which is " + (double)Math.round((double)num / (double)sum * 10000)/100 + "% of the sum.");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.