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: 3934919 • 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


package doubleconstant;

import java.util.Scanner;

public class DoubleConstant {
public void readDouble(){
Scanner sc = new Scanner(System.in);
double number;
boolean flag = false;

try{
System.out.println("Enter non-negative double constant");
number = sc.nextDouble();
System.out.println("Square of "+number+"="+(number * number));
//System.exit(1);
}
catch(Exception e){
System.out.println("Goodbye! not a Double constant re-enter ...");
readDouble();
}
  
  
}
public static void main(String[] args) {
DoubleConstant dc = new DoubleConstant();
  
dc.readDouble();
  
}
  
}

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