Hello I'm having a little trouble in understanding this homework. I just started Java a few weeks ago and we just started on building classes so here is the question.
The problem: I'm having a trouble with the first constructor and setRadius I generally don't know what to do in them. Do I input into setRadius and send that value to that constructor. What do I do with the constructor?
Write a Circle class that has the following fields:
radius: a double
PI: a final double initialized with the value 3.14159
The class should have the following methods:
Constructor: accepts the radius of the circle as an argument.
Constructor: a no-arg constructor that sets the radius field to 0.0.
setRadius: a mutator method for the radius field.
getRadius: an accessor method for the radius field.
getArea: returns the area of the circle, which is calculated as area = PI * radius * radius.
getDiameter: returns the diameter of the circle, which is calculated as diameter = radius * 2.
getCircumference: returns the circumference of the circle, which is calculated as circumference = 2 * PI * radius.
Write a program that demonstrates the Circle class by asking the user for the circle's radius, creating a Circle object, and then reporting the circle's area, diameter, and circumference.
So I wrote this code:
public class CircleClass {
final double PI = 3.14159;
double radius;
// this constructor allows the input of the user
public CircleClass (double rad){
radius = rad;
}
// this is the default constructor in case of no user input
public CircleClass (){
radius = 0;
}
// this method allows you to set the radius
public void setRadius (double input){
//CircleClass input;
radius = input;
}
// value returners //
// returns radius
public double getRadius (){
return radius;
}
// returns area
public double getArea (){
return PI * radius * radius;
}
// returns diameter
public double getDiameter(){
return radius * 2;
}
// returns circumference
public double getCircumference(){
return 2 * PI * radius;
}
}
So I'm confused as to the first method and also I may have made a mistake somewhere else in this program if you see something and you think I should know let me know please.
When you create an instance / object of a class, this basically calls the constructor (default / parameterized) constructor of the class.
CircleClass circleClass = new CircleClass(10);
This will call the parameterized constructor (first constructor in your code) of your class and will set the value of the radius as 10.
CircleClass circleClass = new CircleClass();
This will call the default constructor (no-arg, second constructor in your code) of your class and will set the value of the radius as 0.
If you want to set the value of the radius using the method setRadius(double), it should be done using an object of the class. Since, the methods of a class can be accessed using the objects of the class.
It can be done as follows:
Scanner in = new Scanner(System.in);
CircleClass circleClass = new CircleClass(); // calls the no-arg constructor
System.out.println("Enter the radius of the circle : ");
double radius = in.nextDouble();
circleClass.setRadius(radius); // this sets the radius of the circle using the method setRadius(double) of the class
Methods can also be called in java using class names if the method is defined as public static. Consider the code fragment:
public class Class1{
public static final void PrintMessage(){
System.out.println("Just prints a message");
}
}
The method PrintMessage(void) can be called using the class name as follows:
Class1.PrintMessage(); // Calls the method PrintMessage(void)
Moreover, I don't see any mistakes in your code given the problem statement.
You might however want to make use of the 'this' variable for your class variables. Many a times we might run out of meaningful names for variables (in your case you have used input as a variable name for radius in your setRadius(double) method which may not make much sense to another programmer). However, if you make use of the 'this' variable you can avoid this.
public class CircleClass{
double radius; // class variable
public CircleClass(double radius){
this.radius = radius; // this.radius -> refers to the class variable
}
public void setRadius(double radius){
this.radius = radius; // radius -> refers to the variable passed as argument
}
}
Just a small tip, works wonders.
By creating the main method (the method that actually does something with the program you've created), you might get a better understanding:
First include the below import at the top of your java document (outside the class). This will allow you to use built in java methods that will handle user inputs:
import java.util.Scanner;
Then in the main method:
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
CircleClass cc = new CircleClass(input.nextDouble());
System.out.println(cc.getArea());
}
Inside the main method, you first create a Scanner object, that we give the name "input", (from the Scanner class that we imported). This will allow you to take user inputs.
Then create a CircleClass object (that I named cc, you can name it whatever you want). This object is directly referencing the constructor in your class, as in the method with the same name as the class (CircleClass()). Now, since your constructor takes a parameter with the data type double, we also need to provide a "double" parameter when we create the object. Which we set to the user input (input.nextDouble(), <-- This is how you do that using the Scanner class).
Then at the bottom I simply just print out one of the return methods that you created, in this case getArea(). But note that you put cc.getArea(), since "cc" is the name of the CircleClass object. Creating the CircleClass object allows us to use the methods inside of the CircleClass class in that way.
Hope this didn't get too confusing.
You could create two instance of CircleClass class.
CircleClass uncircle = new CircleClass(); //Default constructor
CircleClass circle = new CircleClass(5.7);
The method uncircle.getRadius() would return 0. I suggest you try circle.getRadius() to check the output.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
The given problem was to create two Java classes, one with constructor methods and the other with a main method, calling the first.
The second half won't compile due to a "Error, cannot find symbol" with symbols symbol: method getArea()
and location
location: variable radius of type Circle
Prof said to check there was something off with my usage of printf, but that's not what's causing the compile errors, is it?
I've done some quick searching for similar problems but a lot of issues people with the same errors were having were related to their class and methods being private.
// Class I'm trying to call from
public class Circle
{
double radius;
public Circle(double r)
{
radius = r;
}
public Circle()
{
radius = 0.0;
}
public void setRadius(double r)
{
radius = r;
}
public double getRadius()
{
return radius;
}
public double area()
{
return Math.PI * Math.pow(radius, 2);
}
public double diameter()
{
return radius * 2.0;
}
public double circumference()
{
return Math.PI * radius * 2.0;
}
}
// Seperate java program, used to call Circle.java
import java.util.Scanner;
public class CircleDemo
{
public static void main(String[] args)
{
String input;
double value;
Circle radius = new Circle();
System.out.printf("Enter the radius"+
"of a circle");
Scanner keyboard = new Scanner(System.in);
input = keyboard.nextLine();
value = Double.parseDouble(input);
radius.setRadius(value);
System.out.printf("Area: " + radius.getArea()
+ "\n Diameter: " + radius.getDiameter() +
"\nCircumference: " + radius.getCircumference());
System.exit(0);
}
}
Error output:
CircleDemo.java:18: error: cannot find symbol
area = radius.getArea();
^
symbol: method getArea()
location: variable radius of type Circle
CircleDemo.java:19: error: cannot find symbol
diameter = radius.getDiameter();
^
symbol: method getDiameter()
location: variable radius of type Circle
CircleDemo.java:20: error: cannot find symbol
circumference = radius.getCircumference();
^
symbol: method getCircumference()
location: variable radius of type Circle
3 errors
You're looking for the wrong method names.
You've defined the method circumference(), but are calling getCircumference(). You've define the method area(), but are calling getArea().
Either rename the methods in Circle, or change the methods called from main.
Right off the bat, it appears as if you're calling the wrong methods.
If you are trying to use getters and setters in Java you have to actually create a method for getting and a method for setting.
Java doesn't automatically give you the values if you just call getDiameter(). You need to actually create a method called getDiameter() then you can call it.
Let me know if that fixes your problem!
You're using methods that do not exist. getDiameter(), getArea() and getCircumference() are not declared in your class Circle. I think you're trying to call diameter(), area() and circumference(). Getters and setters must be declared in the class with its own name; they are not automatically created or something like that.
In my Java basic class my teacher told me to comment any arbitrary choice that I make when I write a default constructor for a class. (She told us that we must create a default constructor for every class that we design) So for example, I'm writing a class named RoomDimension, and I created a default constructor as follows:
public class RoomDimension {
//Fields
private double length; //Length of a carpet
private double width; //Width of a carpet
/**
*
*/
public RoomDimension(){
length = 0.0;
width = 0.0;
}
I'm using here 0.0 as my flag to indicate the user has entered nothing or an invalid input. Should I then comment the fact that 0.0 is used as an indication of an invalid input in the documentation comment(/**/)? I know that if I were to use -1 as my flag (or an initialization of a field in default constructor), I would definitely comment that -1 indicates an invalid input because I made that decision arbitrarily. I'm asking whether 0 has to be commented or not because I don't know if 0 is an arbitrary choice or not. Would you, as a programmer, bother to indicate that? Or, is it okay if I just assume that the user knows it without telling them?
As to whether zero should be commented, I think it would be best to indicate it is a flag in order to remind yourself in the future, or any other programmer that looks at your code.
As for using zero as a flag, I think it would be better practice to throw an exception when length and height are less than or equal to zero. It would be easier to read in the future, and more efficient to handle when a user does enter a non-positive number.
She told us that we must create a default constructor for every class
that we design
And I told for my teacher: Who don't know is teaching, who know is doing!
If you don't create a default constructor, the compiler will do it, did you know? - how about your teacher?
Many tools, which generates, transform data will cry, nags, crash if they don't find a COMPILED "default constructor". But they will completely ignore the comments.
So back to your class:
public class RoomDimension {
static {
System.out.println("I an a static initializer, If the classloader will touch your class, I will be called first! ex. RoomDimension.anyStaticmethod() or before new RoomDimension()");
}
{
System.out.println("I am instance initializer. whenever you call any constructor, I will run before the constructor body, try me with: new RoomDimension()");
}
//Fields
private double length; //Length of a carpet
private double width; //Width of a carpet
public RoomDimension() {
length = 0.0;
width = 0.0;
}
}
By the way in your code:
public RoomDimension() {
length = 0.0;
width = 0.0;
}
it is completely useless, because before constructor, it will be an initialisation and that will do exactly the same, because you have declared as properties and they will be initialize, before constructor:
private double length; //Length of a carpet
private double width; //Width of a carpet
If you want to know it is initialized or not, use Double instead of double and check for null value.
Ex:
private Double length; //Length of a carpet
private Double width; //Width of a carpet
I would set the values of those to be nullable.
public class RoomDimension
{
private double? length;
private double? width;
}
public RoomDimension()
{
}
What this does for you is allow the values of length and width to take the value of null. So when you call the default constructor, they are automatically set to null.
This will help you start thinking in terms of objects, because when you have objects that contain other objects you cant set all the contained objects to 0.0, you just create a null object. Also when you perform actions on that object you just check if its null beforehand this helps to avoid null reference exceptions.
Write a Temperature class that represents temperatures in degrees in both Celsius and Fahrenheit, using a floating-point number for the temperature and character for the scale: either āCā for Celsius or āFā for Fahrenheit. The class should have
Four constructors:
one for the number of degrees,
one for the scale,
one for both the degrees and the scale, and
a default constructor.
For each of these constructors, assume zero degrees if no value is specified and Celsius if no scale is given."
Hey there I am an amateur java programmer... I have been asked to do the above statement and I am not all that familiar with constructors but I'm open to any knowledge :) obviously I'm not asking for someone to give me an answer to my question but maybe someone can give me some advice on how I get started... here's what I have done so far:
public class TemperatureApparatus {
public class temperature{
private float c;
private float F;
public temperature(){
}
public temperature(){
}
public temperature(){
}
public temperature(){
}
}
public static void main(String[] args) {
}
}
Four constructors: one for the number of degrees, one for the scale,
one for both the degrees and the scale, and a default constructor.
These are your constructor arguments. Arguments are passed into constructors and methods via parameters which are listed within the parentheses of the method.
You've got the format of a constructor correct. It's essentially a method that has the same name of the class and no return type. Now you need to add arguments.
The default constructor has no arguments:
public Temperature() { //Class names should be capitalized!
//Default constructors often do nothing, but you can set default values here if you want
}
Here's a signature for a constructor taking the degrees only:
public Temperature(float degrees) {
//Assign the "degrees" argument to an instance variable here
//You might consider assigning a value to a "scale" variable by default as well
}
This assignment probably wants you to fill in that constructor's body, so assign the given value to a float in the class. Now make constructors for the other desired arguments. Since the assignment wants 'F' or 'C' for the scale, you can safely use char as the argument for that data.
Once you've completed the assignment, you might consider challenging yourself with this: Given that a user could now have a Temperature object with a float degree and a char scale, how might you implement a getTemperature() method?
Oh, and there's no reason for you to nest classes like you are. Put Temperature in a separate class from your class that runs main if you need to make a runnable answer.
Here you go
public class Temperature {
private float temp;
char scale;
//first constructor
/*
*Notice how in this first constructor, I put scale
*as 'C' since there was no char value being passed
*as a parameter (no char scale inside the brackets)
*Now i did get a float temp passed a a parameter so
*I set whatever that temp is to the temp of this class
*also known as this.temp (this refers to THIS class
*/
public Temperature(float temp) {
this.temp = temp;
scale = 'C';
//other way
//this(temp, 'C');
}
//second constructor
/*
*Now this constructor is the exact same case at the
*first one, except this one has the char scale passed.
*Since no temp is passed, I set it to 0 as no value is specified
*/
public Temperature(char scale) {
this.scale = scale;
temp = 0;
//other way
//this(0, scale);
}
//third constructor
/*
*This third one is having both temp and scale being specified
*which means you don't need to put any initial value (0 and Celcius)
*Just set these objects to whatever is being passed by through the
*parameters
*/
public Temperature(float temp, char scale) {
this.temp = temp;
this.scale = scale;
}
//fourth constructor
/*
*This last one has no parameters through so
*you can just set both the scale and temp to
*0 and 'C' respectively.
*/
public Temperature() {
temp = 0;
scale = 'C';
//other way
//this(0, 'C');
}
}
Sorry if this is a bit vague. I am new to learning Java.
In my program I have two classes and one of the classes is for user input. The other class calculates that user input and then returns the calculations to the other class. In my calculations class I'm pretty sure I'm making myself work harder and than I should be. I want to have the result of my user input multiplied together but doing that in the calculations class.
Here is my Calculations class.
class Calculations{
double length, width ;
public double floorArea (double length, double width){
return length * width ;
}
public double floorAreaCost (double length, double width) {
return length * width * 6.50 ;
}
public double serviceCharge (double length, double width){
return length * width / 10 + 12.50 ;
}
}
What I want to be able to do is have return length * width = area. Then use that area variable for future reference in the floorAreaCost method and the service charge method. So instead of return length * width * 6.50 I would have area * 6.50
Here's my user input class as well.
import java.util.Scanner;
public class ApartmentUser{
static Scanner input = new Scanner(System.in);
public static void main (String args[]){
int length, width;
System.out.println("Enter the length of the apartment floor: " );
length = input.nextInt();
System.out.println("Enter the width of the apartment floor: " );
width = input.nextInt();
Calculations area = new Calculations();
System.out.println("The area of the apartment floor is: " + area.floorArea(length, width));
Calculations cost = new Calculations();
System.out.println("The cost of the apartment is: " + cost.floorAreaCost(length, width));
Calculations charge = new Calculations();
System.out.println("The service charge cost is: " + charge.serviceCharge (length, width));
}
}
Your methods should call the floorArea method, so for example method shown below
public double floorAreaCost (double length, double width) {
return length * width * 6.50 ;
}
would become
public double floorAreaCost (double length, double width) {
return this.floorArea(length, width) * 6.50 ;
}
That way, the floor area calculation is encapsulated inside one method only and can easily change in one step
First of all you shouldn't make so many Calculations objects, one is enough.
So what you should do is give the Calculations class a constructor like this.
class Calculations{
public double length, width, area;
public Calculations (int length, int width) {
this.length = length;
this.width = width;
area = width * length;
}
Now when you create youre Calculations object:
Calculations floor = new Calculations(int length, int width);
You directly have the area calculated and you can call the methods without having to input the parameters, because they're already saved in the Calculations class.
You can also work with multiple "rooms", because the informations are saved in the Calculations class.
Hope i could help you.
As written, your Calculations class defines a "stateless" object.
Within each function, the function parameters length and width
hide the member variables length and width,
so that the member variables are never use at all.
You should be able to delete the declaration of those member variables
without noticing any change in the behavior of your program.
This is not necessarily a bad thing. Stateless classes can be very useful.
For example, because Calculations is stateless, you do not need to
allocate three different instances to perform your three different functions.
You can call all the functions on the same instance, because none of the
functions can affect the "state" of the object and therefore cannot have
any hidden "side effects" on the results of functions called later.
The return from each function is determined just by the values you
pass to its two parameters.
The program does end up multiplying the same length and width together
three times when once would have been enough.
You will hardly notice the extra computing time in this example
(it is vastly overshadowed by everything else going on here),
but if you had to do millions of these calculations for one user input
you might then notice a difference.
One way to avoid the redundant multiplications
is to return area from the floorArea function,
but pass area (not length and width) as a single parameter to
each of the other functions.
You might also consider creating member variables of Calculations
to store the numbers 6.5, 10, and 12.5 that you use in some of your functions.
That would allow you to give those numbers meaningful, descriptive names.
It would also permit a more sophisticated version of the program to accept
new values of those constants to use in a Calculations object,
allowing the store to change its pricing without rewriting its software.
If you set those values during the construction of a Calculations object
and do not change them in any of the other functions, the object
is still stateless.
Or you could decide to change the class some other way. I see at least three other answers already, each of which proposes a legitimate design of a Calculations class, no two of those designs the same.
First off all when you define fields in your class, it's common practice to define the scope of the variable. So it would look something like this. Which only makes the variable accessible within the class, if you would access it from the main method, you should declare em public. But add your area as a variable.
private double area ;
You need to store your calculated Area on the object, use the keyword this for accessing that variable. When operations on the same object is done, it can be fetched in a similar fashion.
Update your code to this:
public double floorArea (double length, double width){
this.area = length * width;
return this.area;
}
public double serviceCharge (){
return this.area / 10 + 12.50 ;
}
OK so I can't understand why it says the method isn't being used locally.... The private String formatNumber() method is saying this.
Basically what I need to do is have a method that returns the circumference
- another method that rounds numbers to 2 decimal places and returns a string
- and another method that returns the formatted version of circumference...
It's not hard to see what I'm trying to do, but it gives me the above stated error and I can't figure it out.
//figures out circumference
public double getCircumference(){
circumference = 2 * Math.PI * radius;
return circumference;
}
//takes string and turns back into a double
public double getFormattedCircumference(){
double x = Double.parseDouble(format);
return x;
}
//this method is giving the error of not being used locally...
//method takes double and turns to string so that it can be formatted and it
has to be a string
private String formatNumber(double x){
x = circumference;
NumberFormat number = NumberFormat.getNumberInstance();
number.setMaximumFractionDigits(2);
String format = number.format(x);
return format;
}
You've declared the private method but you've not used it in your current code anywhere and so the compiler is warning you of this (check your program to see if you're calling this method anywhere).
Incidentally, what you're seeing is a warning not an error. Your code should still compile, and the program will still run (if there are no errors present).
Edit 1
You've a serious problem with the method, and maybe more than one, in that it takes in a double parameter and then promptly discards it. Why? If you want to format the number that is passed in as a parameter, then you don't want to discard that parameter. Also, do you want to make this method public so that it can be called by objects outside of this class? Also, will the method have state or will it be stateless? Will it use the fields of the class, or will it only format the number passed into it. If the latter, than it should be a static method.
I got it all figured out. I was making it harder than it actually was.
//figures out circumference
public double getCircumference(){
circumference = 2 * Math.PI * radius;
return circumference;
}
public String getFormattedCircumference(){
return formatNumber(getCircumference());
}
//formats to two decimal places.
private String formatNumber(double x){
NumberFormat number = NumberFormat.getNumberInstance();
number.setMaximumFractionDigits(2);
String format = number.format(x);
return format;
}