Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java Program: Write a java program in which main prompts for and reads in a doub

ID: 3934518 • Letter: J

Question

Java Program:

Write a java program in which main prompts for and reads in a double constant and then displays the square of the constant. If the user does not enter a double constant, your program should reprompt the user for a valid input. [Do not use hasNextDouble to determine if the inputs is invalid. Instead, catch the exception that nextDouble throws if the input is invalid.] Your program should use the prompt and error messages illustrated by the following sample session:

Enter non-negative double constant hello Not a double constant. Re-enter goodbye Not a double constant. Re-enter 4 Square of 4 = 16.0

Do not use hasNextDouble to determine if the inputs is invalid. Instead, catch the exception that nextDouble throws if the input is invalid.

Explanation / Answer

import java.util.*;
public class DoubleSqr {

   public static void main(String[] args) throws java.util.InputMismatchException {
  
       // TODO Auto-generated method stub
      
       try
       {
       double n1, sqr;
       Scanner sc=new Scanner(System.in);
      
       System.out.println("Enter a number");
       n1=sc.nextDouble();
       sqr=n1*n1;
       System.out.println("Squire of"+n1+"is"+sqr);
       }
       catch(java.util.InputMismatchException E)
       {
           System.out.println(" Invalid Input ==>" +E);
       }

   }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote