Ask Question
3 July, 12:52

Write code that prompts for three integers, averages them, and prints the average. Make your code robust against invalid input; if the user types a non-number, re-prompt with the same prompt message. (You may want to look at the getInt method discussed in Chapter 5. You can call that method in your solution if you like.) Here is an example dialogue: Type an integer: 5 Type an integer: 2 Type an integer: 17 Average: 8.0

+4
Answers (1)
  1. 3 July, 13:04
    0
    The program to this question can be given as:

    Program:

    import java. util.*; / /import package for user input.

    public class Main / /define class-main

    {

    public static void main (String ar []) / /define main function

    {

    try / /try block

    {

    int a, b, c, sum=0; / /declare variable

    double average;

    Scanner ob = new Scanner (System. in); / /create Scanner class Object

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

    a = ob. nextInt (); / /input number.

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

    b = ob. nextInt ();

    System. out. print ("Enter third number : ");

    c = ob. nextInt ();

    //print numbers

    System. out. print ("/nFirst number:"+a);

    System. out. print ("/nSecondnumber:"+b);

    System. out. print ("/nThird number:"+c);

    sum = sum+a+b+c; / /Sum

    average = sum/3; / /Average

    System. out. print ("/nAverage:" + average); / /print average

    }

    catch (Exception e) / /catch block.

    {

    System. out. print ("Enter number only ... !"); / /message

    }

    }

    }

    Output:

    Enter first number 5

    Enter second number 2

    Enter third number 17

    First number: 5

    Second number: 2

    Third number: 17

    Average: 8.0

    Explanation:

    In the above program firstly we import packages for user input. Then we declare the main class. In the main class, we define the main function in the main function we use the exception handling. In the exception handling, we use try and catch block. In the try block firstly we declare variables then create a scanner class object and take input from the user. After user input we add all numbers into the sum variable then we take average in the average variable and print all values. If the user doesn't input a number then we use the catch block in this block it prints a simple message that is "Enter number only ... !"
Know the Answer?
Not Sure About the Answer?
Get an answer to your question ✅ “Write code that prompts for three integers, averages them, and prints the average. Make your code robust against invalid input; if the user ...” in 📙 Computers & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers