T. Wielgos - 10 months ago 56

Java Question

how would i ask the user for the radius? I'm pretty sure it will be an easy fix but i'm just not sure how to do it. Here is my code so far.

`import java.util.Scanner;`

public class CircleDriver

{

public static void main(String[] args)

{

Scanner input = new Scanner(System.in);

Circle circle1 = new Circle();

circle1.setRadius(20);

System.out.println("Enter the radius of a circle " + circle1.getRadius());

System.out.println("Area = " + circle1.calculateArea());

System.out.println("Diameter = " + circle1.calculateDiameter());

System.out.println("Circumference = " + circle1.calculateCircumference());

}

}

Circle class :

`public class Circle`

{

private double radius;

private final double PI = 3.14159;

/**

* this method calculates the area of the given radius

* @return

*/

public double calculateArea() {

double area;

area = (PI * radius * radius);

return area;

}

/**

* this method calculates the diameter of the given radius

* @return

*/

public double calculateDiameter() {

double diameter;

diameter = (radius * 2);

return diameter;

}

/**

* this method calculates the circumference of the given radius

* @return

*/

public double calculateCircumference() {

double circumference;

circumference = (2 * PI * radius);

return circumference;

}

/**

* this method sets the radius of the object

* @param radius

*/

public void setRadius(double radius) {

this.radius = radius;

}

/**

* this radius returns the radius given

* @return

*/

public double getRadius() {

return radius;

}

}

Answer Source

Try this :

```
System.out.println("Enter the radius pls :");
try {
circle1.setRadius(input.nextDouble());
} catch (InputMismatchException e){
System.out.println("ERROR : Invalid input !");
}
```