93.5k views
3 votes
Write a progam to add to simple number and stores into an array and finds their sum and average​

1 Answer

1 vote

Here's a Java program that prompts the user to input two numbers, stores them in an array, calculates their sum and average, and outputs the results:

import java.util.Scanner;

public class AddNumbers {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

// Prompt the user to input two numbers

System.out.print("Enter the first number: ");

double num1 = input.nextDouble();

System.out.print("Enter the second number: ");

double num2 = input.nextDouble();

// Store the numbers in an array

double[] nums = {num1, num2};

// Calculate the sum and average

double sum = nums[0] + nums[1];

double avg = sum / 2;

// Output the results

System.out.println("The sum of " + nums[0] + " and " + nums[1] + " is " + sum);

System.out.println("The average of " + nums[0] + " and " + nums[1] + " is " + avg);

}

}

This program uses a Scanner object to read in two numbers from the user. It then stores the numbers in an array, calculates their sum and average, and outputs the results to the console using System.out.println().

Note that this program assumes that the user will input valid numbers (i.e., doubles). If the user inputs something else, such as a string or an integer, the program will throw a java.util.InputMismatchException. To handle this exception, you could wrap the input.nextDouble() calls in a try-catch block.

User Teejay Bruno
by
7.8k points