Getting .set to work with an object array in Java - java

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.

Related

How do I create a loop to iterate objects and display calculations of the objects from the array?

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.");
}
}
}
}

why class Circle is not working in Java or I made any mistake, Please answer

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());
}
}

My Java Code keeps returning wrong values?

public class CirclePlus implements Relatable {
public double radius = 0;
final double PI = 3.14159;
CirclePlus(){}
public CirclePlus(double radius) {
radius = radius;
}
public double getArea() {
return PI * (radius * radius);
}
public double isLargerThan(Relatable other) {
CirclePlus otherCirc = (CirclePlus)other;
if (this.getArea() < otherCirc.getArea())
return -1;
else if (this.getArea() > otherCirc.getArea())
return 1;
else
return 0;
}
/// Main class below
public static void main(String[] args) {
CirclePlus c1 = new CirclePlus(50);
CirclePlus c2 = new CirclePlus(0);
if(c1.isLargerThan(c2) == 1) {
System.out.println("c1 is bigger!");
}
else
System.out.println("c1 has the same size as that of c2 or smaller than"
+ " c2!");
}
Output is always:
"c1 has the same size as that of c2 or smaller than"
No matter what I change the radius of the 2 circles to.
This is my code, it keeps returning 0 in the final else statement but even when the conditions are met in the if/else if statements, it ignores them and just goes to the bottom and returns 0;
Can you help me to fix this? Also, just so I can learn more, can you explain why java is doing this?
Just the help will be okay too, thanks so much!
The error occurs in the following piece of code:
[...]
public double radius = 0;
[...]
public CirclePlus(double radius) {
radius = radius;
}
Here, Java tries to assign the local method variable radius to itself, which has no effect on your class member variable radius.
To avoid this problem, you have to either qualify the left hand side of the assignment like this
public CirclePlus(double radius) {
this.radius = radius;
}
or use a different name for the local variable like this
public CirclePlus(double r) {
radius = r;
}
so that Java can distinguish the local method variable from the class variable.
Some other minor points: your class variable radius should be private rather than public and your isLargerThan method should return an int instead of a double.
Also, it would be more logical if a method called isLargerThan would return a boolean. You could also implement the Comparable interface:
int compareTo(CirclePlus other) {
return Double.compare(this.getArea(), other.getArea());
}

Adding objects with different parameter into the array

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.

Java Programming Debug Quiz

This quiz is in two parts. First is
public class FixDebugBox {
private int width;
private int length;
private int height;
private double Volume;
public void FixDebugbox() {
length = 1;
width = 1;
height = 1;
}
public FixDebugBox(int width, int length, int height) {
width = width;
length = length;
height = height;
}
public void showData() {
System.out.println("Width: " + width + " Length: " +
length + " Height: " + height);
}
public double getVolume() {
double vol = length * width * height;
return Volume;
}
}
The code above is one half of the quiz, it have the code above complied correctly but the second part I can't
public class FixDebugFour3
// This class uses a FixDebugBox class to instantiate two Box objects
{
public static void main(String args[])
{
int width = 12;
int length = 10;
int height = 8;
FixDebugBox box1 = new FixDebugBox(width, length, height);
FixDebugBox box2 = new FixDebugBox(width, length, height);
System.out.println("The dimensions of the first box are");
box1.showData();
System.out.println("The volume of the first box is");
showVolume(box1);
System.out.println("The dimensions of the first box are");
box2.showData();
System.out.println("The volume of the second box is");
showVolume(box2);
}
public void showVolume() {
double vol = FixDebugBox.getVolume();
System.out.println(vol);
}
}
I keep getting an error with double vol = FixDebugBox.getVolume(); error: non-static method getVolume() cannot be referenced from a static context
FixDebugBox.getVolume();
getVolume is non static method you can not call this with class name, its a public method which you need object to call it.
public void showVolume(FixDebugBox box) {
double vol = box.getVolume();
System.out.println(vol);
}
Now give me the prize. :D
I think you already answered yourself. You need to hold a reference to an instance of FixDebugBox in order to call its non-static methods.
As the error message says, you can't call a non-static method from the static context that is the main method. While you could turn your showVolume() to be a static method and take a FixDebugBox instance as an argument, seeing how FixDebugBox objects already have a getVolume() method, just call it for each instance:
System.out.println(box1.getVolume());
...
System.out.println(box2.getVolume());
Also, don't change the name of your Volume variable to volume. You should use camelCase.
If you move
public void showVolume() {
double vol = FixDebugBox.getVolume();
System.out.println(vol);
}
to the class FixDebugBox
and remove the getVolume() method inclass FixDebugBox , and change the showVolume() method to:
public void showVolume() {
double vol = length * width * height;
Volume = vol;
System.out.println(Volume);
}
That would fix your program. Also boxVolume would be a better name instead of Volume, since variables are not supposed to be written with a capital letter.

Categories