So I have this question,
Class circle:
Contains an appropriate attribute to store the radius.
Contains a constructor with one parameter to set the radius.
Contains set and get methods.
Contains a method for calculating the area and another method for calculating the
circumference.
Circle should contain an appropriate attribute to keep track (count) of the number of
Circle objects instantiated.
Class TestCircle:
Create an array of 10 circles of radii 1.0 , 2.0, ..., 10.0.
Print the area and circumference of each circle.
Retrieve and print the number of circles that have been instantiated.
My code is:
public class Circle {
public double radius= 0.0;
public int counter;
public Circle (double radius){
this.radius = radius;
counter++;
}
public Circle (){
}
public void setRadius (double radius){
this.radius = radius;
}
public double getRadius (){
return radius;
}
public double Area (){
return 3.14*radius*radius;
}
public double Circumference (){
return 2*3.14*radius;
}
}
public class TestCircle {
public static void main (String args []){
Circle [] arr = new Circle [10];
System.out.println ("The circumference" + arr.Circumference());
System.out.println ("The area" + arr.Area());
System.out.println ("The number of circles" + arr.counter);
}
}
My question is:
How am I supposed to create 10 circle objects with different radius and add it to the array?
I know that the idea was to add the objects to the array by using the for loop but I couldn't add the radius into the process.
Thank you.
Your code could change like
public class Circle {
private double radius;
private static int numberOfCircles = 0;
public Circle (double radius){
this.radius = radius;
numberOfCircles++;
System.out.println("The circumference : " + getCircumference());
System.out.println("The area : " + getArea());
}
public double getRadius (){
return radius;
}
public double getArea (){
return 3.14*radius*radius;
}
public double getCircumference (){
return 2*3.14*radius;
}
public static int getNumberOfCirclesCreated(){
return numberOfCircles;
}
}
public class TestCircle {
public static void main (String args []) {
Circle [] circles = new Circle [10];
for(int counter=0;counter< circles.length;counter++){
circles[counter]=new Circle((double)(counter+1));
}
System.out.println("Number of circles : " + Circle.getNumberOfCirclesCreated());
}
}
Create for loop that iterates through each array cell. You then create a new Circle object and call its setRadius function. You then set array Cell to equal the Circle object and continue iterating till the array is filled.
Additionally, your counter should be static (as corrected by Fildor). Consider also setting radius as private, seeing as you put in getter/setters.
Related
I am new to Java and currently doing a small project to learn.
These are the requirements for the project:
Create a class named Circle with a field named radius.
Include default constructor
Include a default constructor that sets the radius to 1 by default.
Include another constructor that receives the radius and sets the radius to the value
received.
Include a method that returns the area of the circle.
-Include another method that returns the circumference of the circle.
Use the PI constant of the Math class for this calculation.
Create a class named TestCircle whose main() method declares 5 Circle objs and stores them in an array
5 circle objects will have different radius values
Using a loop, iterate the objects and display areas and circumference of the objects from the array
if the radius is one, display a message saying "This is a unit circle".
I managed to complete some of the requirements to the best of my ability but I don't know how to
Using a loop, iterate the objects and display areas and circumference of the objects from the array. If the radius is one, display a message saying "This is a unit circle".
class Circle {
double radius;
//constructor to default radius to 1
public Circle() {
this.radius = 1;
}
//constructor to receive values and set it as radius
public Circle(double [] circlesRad) {
this.radius = circlesRad[0];
}
public double computeArea(){
return Math.PI * (radius * radius);
}
public double computeCircumference() {
return Math.PI *2*radius;
}
}
public class TestCircle {
public static void main(String[] args) {
Circle c1 = new Circle();
double circlesRad[] = {1, 34, 56, 23, 93, 18};
for (double rad : circlesRad) {
System.out.println("Circle:"+"\nArea: "+ c1.computeArea()+"\nCircumference: "+ c1.computeCircumference());
if (rad == 1){
System.out.println("Circle:"+"\nArea: "+ c1.computeArea()+"\nCircumference: "+ c1.computeCircumference());
System.out.println("This is a unit circle.");
}
}
}
}
I know its very wrong, and I apologise.
Any help would be much appreciated.
Below is the code:-
class Circle {
double radius;
//constructor to default radius to 1
public Circle() {
this.radius = 1;
}
//you should consider this as just passing a radius value.
public Circle(double circlesRad) {
this.radius = circlesRad;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public double computeArea(){
return Math.PI * (radius * radius);
}
public double computeCircumference() {
return Math.PI *2*radius;
}
}
public class TestCircle {
public static void main(String[] args) {
Circle[] circles = {new Circle(1), new Circle(34), new Circle(56),
new Circle(23), new Circle(93), new Circle(18)};
for (Circle circle : circles) {
System.out.println("Circle:"+"\nArea: "+ circle.computeArea()+"\nCircumference: "+ circle.computeCircumference());
if (circle.getRadius() == 1){
System.out.println("This is a unit circle.");
}
}
}
}
I am trying to calculate the area of the circle using class and object in Java, but the output is not as I want. I want an answer as 78.5 but the area = 0.0, why? Here is the code below-
package com.company;
import java.util.Scanner;
class Circle{
double r;
double area= Math.PI*r*r;
}
public class practice {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Circle c = new Circle();
System.out.print("Enter the radius of circle: ");
c.r = sc.nextDouble();
System.out.println("The area of circle is: "+ c.area);
}
}
The result I got is-
Enter the radius of circle: 5
The area of circle is: 0.0
Process finished with exit code 0
Try this code, should work. Compare with what you have done so far: You are calculating area before the user has entered data. I suggest you to read about constructors
package com.company;
import java.util.Scanner;
class Circle{
double r = 0.0;
double area= 0.0;
public Circle( double r ){
this.r = r;
this.area = Math.PI*this.r*this.r;
}
}
public class practice {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the radius of circle: ");
Circle c = new Circle( sc.nextDouble() );
System.out.println("The area of circle is: "+ c.area);
}
}
At new Circle(), r is initialized to be 0 (since no explicit assignment is given) and area is calculated with this and thus store the value 0.
At c.r = sc.nextDouble();, c.r is reassigned to hold the scanned value. However, area will not be automatically recomputed based on this assignment and hence remains at 0.
You have to understand that the code at the constructor will be run only once when an object is created.
If you have no constructor (like in your example code above) then the code will be run when the program is run. The values of not initialized double values will be 0.0. That's the problem in your case too. Your area calculation will be translated to area = 3.14 * 0.0 * 0.0. I would suggest following the conventions and best practices this way:
class Circle
{
private double radius = 0.0; // Best practice is to declare the variable private and access it through getters & setters
public Circle(double radius)
{
this.radius = radius;
}
public double calculateArea()
{
return Math.PI * this.radius * this.radius ;
}
public double getRadius()
{
return radius;
}
public void setRadius(double radius)
{
this.radius = radius;
}
}
public class Practice
{
public static void main(String[] args)
{
Circle c = new Circle(5);
System.out.println("Area of this circle is : " + c.calculateArea());
}
}
So I'm trying to make a program where you put in a radius and it spits out the area, diameter etc. but whenever I run the app it crashes. Here's what I've got if anyone can help that would be much appreciated
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
MeasureC[] mc = new MeasureC[5];
int i=0;
int p =5;
for(i=0;i<=p;i++)
{
System.out.println("What do you want the radius to be?");
double UserRad = scan.nextDouble();
mc[i].setRadius(UserRad);
mc[i].setArea();
mc[i].setDiameter();
mc[i].setCircumfrence();
System.out.println(mc[i].getRadius());
System.out.println(mc[i].getArea());
System.out.println(mc[i].getDiameter());
System.out.println(mc[i].getCircumfrence());
}
Here's the second class:
public class MeasureC {
private double radius, area, diameter, circumfrence;
public double getRadius() {
return radius;
}
public void setRadius(double newRadius) {
radius = newRadius;
}
public double getArea() {
return area;
}
public void setArea() {
area = 3.14*radius;
}
public double getDiameter() {
return diameter;
}
public void setDiameter() {
diameter = 2*radius;
}
public double getCircumfrence() {
return circumfrence;
}
public void setCircumfrence() {
circumfrence = 3.14*(2*radius);
}
MeasureC[] mc = new MeasureC[5];
This doesn't create an array of 5 MeasureC objects, it just allocates the space for them in memory. So, currently, every index points to null. That means that in your for loop when you try and access a particular element in your array you will get an error as .setRadius() etc... is not a method of null:
mc[i].setRadius(UserRad); // mc[i] is null
So, to fix this issue, you can create a new instance of your MeasureC class at each iteration and set it at your index:
for(i = 0; i < p; i++) { // set to i < p as max index in your array is 4 (not 5)
mc[i] = new MeasureC();
// code...
}
Replace:
for(i=0;i<=p;i++)
by:
for(i=0;i<p;i++)
as now you iterate 6 times on 5 dimension array and got ArrayIndexOutOfBoundsException
I assume you get a NullPointerException at the line mc[i].setRadius(UserRad);.
Think about what that means. Then it should be obvious what line you have to add before that to fix the problem.
Hint: Think about how Java does array initializations.
Assuming you want the radius to be the only input data allowed, we can try refactoring your code as (see notes below):
public class MeasureC {
private double radius, area, diameter, circumference;
public MeasureC (double radius) {
diameter = 2.0d * radius;
circumference = Math.pi * diameter;
area = Math.pi * Math.pow(radius, 2);
}
public double getRadius(){
return radius;
}
public double getArea(){
return area;
}
public double getDiameter(){
return diameter;
}
public double getCircumfrence(){
return circumfrence;
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int p = 5;
MeasureC[] mc = new MeasureC[p];
for (int i=0; i <= p; i++) {
System.out.println("What do you want the radius to be?");
double userRad = scan.nextDouble();
mc[i] = new Measure(userRad);
System.out.println(mc[i].getRadius());
System.out.println(mc[i].getArea());
System.out.println(mc[i].getDiameter());
System.out.println(mc[i].getCircumfrence());
}
}
Notes:
I expose a single constructor in your MeasureC class which accepts an input radius as a double. Inside that constructor I compute, using that input radius, the diameter, circumference, and area.
Since you only want the circle to be configurable via the radius, I removed setters for the diameter, circumference, and area.
A problem you had in your main() method was that you were not instantiating your MeasureC instances with new. I am doing this now.
Java naming conventions say that variable names should begin with lowercase letters, while class names begin with uppercase. Both are camelcase for subsequent letters. You should stick with this convention.
I have to write a program using constructors which calculates the area of a circle using 5 methods:
Circle: The constructor that creates a circle with radius = 1
setRadius: takes an double argument and sets the radius to the argument
getRadius: returns an double argument with the value of the radius
computeDiameter: calculates the diameter and returns the value of the diameter
computeArea: calculates the area and returns the value of the area
So far, I reached here..
Main Class:
class MyClass{
public static void main(String[] args) {
MyClass1 circle= new MyClass1();
System.out.println(circle.computeArea());
}
}
This is the second class.. I haven't named it Circle though..
public class MyClass1 {
private double radius;
private double diameter;
private double area;
public MyClass1(){
radius= 1.0;
}
public void setRadius(double radius){
this.radius= radius;
}
public double getRadius(){
return radius;
}
public double computeDiameter(){
diameter= 2.0*radius;
return diameter;
}
public double computeArea(){
area= (Math.PI* Math.pow(diameter, 2))/4;
return area;
}
The problem is that the output for the area is giving me 0.0
your diamter is initially 0 and only gets set to the correct value after calling computeDiameter() , so try to replace
area= (Math.PI* Math.pow(diameter, 2))/4;
with area= (Math.PI* Math.pow(computeDiameter(), 2))/4;
In constructor:
public MyClass1(){
radius= 1.0;
}
diameter was not initialized. So it has value 0 set by default.
Your method:
public double computeArea(){
area= (Math.PI* Math.pow(diameter, 2))/4;
return area;
}
uses diameter parameter but it is zero at the moment it is used.
Well you have not given diameter a value, so the diameter is 0.
I built a program that has this method and I also want
to count the number of objects I created. But after running the program. It said that there are 0 objects being created.
Can anyone know why this is not correct? It should say that there
are 4 objects being created.
Here is my codes:
/**
This program implements code for a Circle class,
which has a radius field, set and
get methods, and a getArea method.
Author: Michael Wu.
*/
public class Circle
{
private double radius;
private static int numCircles;
public Circle(double radius)
{
this.radius = radius;
}
//SetRadius method,sets radius.
public void setRadius(double radius)
{
this.radius = radius;
}
//GetRadius method; returns radius.
public double getRadius()
{
return radius;
}
//Constructor increments numbers of circles.
public Circle()
{
numCircles++;
}
//Copy constuctor.
public Circle(Circle c3)
{
radius = c3.radius;
}
//GetNumbercircles method; get number of circles.
public int getNumCircles()
{
return numCircles;
}
//Copy method, copy objects.
public Circle copy()
{
Circle copyObject = new Circle(radius);
return copyObject;
}
//Call the getArea method.
public double getArea()
{
return radius*radius*Math.PI;
}
}
/**
This program created several circle objects and then their areas and radius will be displayed on the screen.
Author: Michael Wu.
*/
public class CircleDemo
{
public static void main(String[] args)
{
int numCircles;
//Create two circle objects.
Circle c1 = new Circle(3.7);
Circle c2 = new Circle(5.9);
Circle c3 = new Circle(c1);
//Declare a circle object.
Circle c4;
//Make c3 reference a copy of a object refferenced by c1.
c4 = c2.copy();
//Display outputs.
System.out.println("The radius for circle1 is "+ c1.getRadius());
System.out.println("The area for circle1 is "+ c1.getArea());
System.out.println("The radius for circle2 is "+ c2.getRadius());
System.out.println("The area for circle2 is "+ c2.getArea());
System.out.println("The radius for circle3 is "+ c3.getRadius());
System.out.println("The area for circle3 is "+ c3.getArea());
System.out.println("The radius for circle4 is "+ c4.getRadius());
System.out.println("The area for circle4 is "+ c4.getArea());
//Get the number of circles.
numCircles = c1.getNumCircles();
System.out.println("There are "+numCircles+" objects being created.");
}
}
You only increment numCircles when you call the Circle constructor with no arguments. But you never call that specific constructor; you call the other constructors.
Increment numCircles on all constructors.
Incidentally, because numCircles is static, the method getNumCircles that returns this number should also be static, and you could invoke it as follows: Circle.getNumCircles().
The constructors you're calling to create the objects (the ones that take a parameter) don't call the no-arg constructor that increments the counter. Try:
public Circle(double radius)
{
this();
this.radius = radius;
}
public Circle(Circle c3)
{
this();
radius = c3.radius;
}
You have to explicitly call this() otherwise the constructors will implicitly call super(), which in your case is the Object constructor.
As other answers have mentioned, you should call your zero argument constructor first via this() in each of your constructors in order to ensure that it is executed. Currently, your code does not invoke the code in the zero argument constructor since it is never called directly, nor is it called when your other constructors are invoked.
Alternatively, you could instead add an inline initialization block below your declaration, e.g:
private static int numCircles = 0;
// Increment numCircles for every object constructed.
{
numCircles++;
}
This is less standard, and possibly worse practice, but it will automatically ensure its execution without needing to increment numCircles in any constructor.
u should initialize numCircles with 0 and increase it on each constructor call, especially because u have multiple constructors u have to keep track that they are all incrementing numCircles. U can call one constructor from the inside of the other, so u may not add equal statements to each constructor.
Move your code 'numCircles++;' to Circle(double radius) constructor. Circle() is not called when you create circle object
public Circle(double radius)
{
this.radius = radius;
numCircles++;
}