How to use constructor in Java - java

Can someone please tell me what's wrong with this simple program? I'm getting output as "0".
package myConst;
public class Doconstructor
{
int length,width;
Doconstructor(int x, int y)
{
int area;
area = length * width;
System.out.println("area ="+area);
}
}
class work
{
public static void main(String args[])
{
Doconstructor d1 = new Doconstructor(10, 15);
}
}

Doconstructor d1 = new Doconstructor(10, 15);
// you are assigning values for x and y
But
Doconstructor (int x,int y)
{
int area; // you are never use x and y values for calculation
area = length *width; // so area remain 0 since current length and width is 0
System.out.println("area ="+area);
}
You need to change your code as follows.
Doconstructor (int x,int y)
{
int area;
this.length=x;
this.width=y;
area = length *width;
System.out.println("area ="+area);
}

Edit like this:-
package myConst;
public class Doconstructor
{
int length,width;
Doconstructor(int x, int y)
{
int area;
this.length=x;//Using this for current object
this.width=y;//Using this for current object
area = length * width;
System.out.println("area ="+area);
}
}
class work
{
public static void main(String args[])
{
Doconstructor d1 = new Doconstructor(10, 15);
}
}
Your output will be:
area =150
Must read this :
http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

You are not setting the values of length and width and by default they are both 0. You might have to do this:
Doconstructor(int x, int y){
int area;
area = x * y;
length = x;
width = y;
System.out.println("Area = "+area);
}

You're not using the variable values you pass to the constructor in it but rather the length and width values that have been initialized to 0. You want area = x * y; instead.

The length and width fields are implicitly initialized to 0. Multiply them and you get 0.
I think what you want is
length = y ;
width = x ;
int area = length * width ;
System.out.println("area ="+area);

You have this:
public class Doconstructor {
int length,width;
Doconstructor (int x,int y)
{
int area;
area = length *width;
System.out.println("area ="+area);
}
}
At no point do you set length or width equal to anything. Their initial values are 0 and your program is doing precisely what you told it to do. area = length * width = 0 * 0 = 0.
You also are not doing anything with the x or y that you passed to the constructor, but this probably was not your intention. When writing programs, you basically need to clearly instruct the computer to do what you want to do. It's not going to guess what you want. If you ignore x and y, and don't assign any values to length or width, then that is precisely what will happen and you cannot be surprised when you see the results you see.

you are writing int length,width at class level so length and width are set to 0 as default.
After that in the constructor you are not setting any values to length and width so you are the values for length and width are 0.Hence area is also 0
Please check this link for list of default values

Constructors are used to create objects and to set the attributes. You are not setting the attributes in your constructor. Here is how your constructor should look like.
Doconstructor(int x, int y){
length = x;
width = y;
}
Secondly you are mixing the logic of a constructor and a method. You are doing the calculation of area, which seems to be a perfect fit for another method in your class. so better move that logic in a separate method:
public int calculateArea() {
int area;
area = x * y;
return area;
}
Finally create an object using constructor to set the attributes length and width. And then call calculateArea method to do the business logic of calculating area.
public static void main(String args[]){
Doconstructor d1 = new Doconstructor(10, 15); // create object and set length & width
d1.calculateArea();
}

you are not assigning the value of x and y to the variables width and length. The default value of width and length are (int) 0. Thats why you are getting the output (0*0=0). First assign the values to the variables or use "area=x*y;" .

Related

Java Box program with multiple methods and constructors

I am a beginner in programming and am having trouble with using constructors, specifically. I have to write a program for one of my labs that must consist only of:
Three instance variables – length, width and height (each of type double)
One instance variables – input (type Scanner) initialized to System.in
Default constructor (no-arg) – initialize all three instance variables to 1
Initial constructor – initialize all three instance variables
Copy constructor – copy Box
inputWidth, inputLength, and inputHeight methods that set the instance variables based on user input have not parameters and do not
return a value.
a displayDimensions method that displays the length X Width X height (separated by “X”) and does not return a value.
a calcVolume method that has no parameters and calculates the volume of the box
We also were given application BoxTest in which the output must
exactly match the following:
Default dimensions are 1.0 X 1.0 X 1.0 with volume of 1.0
Initial dimensions are 8.5 X 11.0 X 1.0 with volume of 93.5
Copied dimensions are 8.5 X 11.0 X 1.0 with volume of 93.5
Update dimensions
Enter length: 1
Enter width: 2
Enter height: 3
Updated dimensions are 1.0 X 2.0 X 3.0 with volume of 6.0
Here's my code:
import java.util.Scanner;
public class Box {
public static void main(String args[]) {
double length, width, height;
Scanner input=new Scanner(System.in);
new Box() { //
Box defaultBox=new Box();
double length = 1.0;
double width = 1.0;
double height = 1.0;
System.out.print("Default dimensions are " + length + " X " + width + " X " + height);
defaultBox.displayDimensions();
System.out.println(" with volume of "+defaultBox.calcVolume());
Box initialBox=new Box(length, width, height);
length = 8.5;
width = 11.0;
height = 1.0;
System.out.print("Initial dimensions are " + length + " X " + width + " X " + height);
initialBox.displayDimensions();
System.out.println(" with volume of "+initialBox.calcVolume());
Box copyBox=new Box(initialBox);
System.out.print("Copied dimensions are " + length + " X " + width + " X " + height);
copyBox.displayDimensions();
System.out.println(" with volume of "+copyBox.calcVolume());
System.out.println("\nUpdate dimensions");
initialBox.inputLength();
initialBox.inputWidth();
initialBox.inputHeight();
System.out.print("Updated dimensions are ");
initialBox.displayDimensions();
System.out.println(" with volume of "+initialBox.calcVolume());
}
double inputLength() {
Scanner input;
double length = input.nextDouble();
}
double inputWidth() {
Scanner input;
double width = input.nextDouble();
}
double inputHeight() {
Scanner input;
double height = input.nextDouble();
}
double displayDimensions(double length, double width, double height) {
Scanner input;
}
double calcVolume() {
}
}
What am I missing? My program will not compile and gives the error message
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error, insert "Identifier (" to complete MethodHeaderName
Syntax error, insert ")" to complete MethodDeclaration
Syntax error, insert ";" to complete MethodDeclaration
Syntax error, insert "}" to complete ClassBody
at Box.main(Box.java:18)
As I said in the comments, you have put everything in main. Don't do that. As it is, your Box class is basically empty, and you are currently almost creating an anonymous sub-class in main. Your directions do not mention a main, but are pretty straight forward. You were supposed to write something like
public class Box {
// Three instance variables – length, width and height (each of type double)
private double length, width, height;
// One instance variables – input (type Scanner) initialized to System.in
private Scanner input = new Scanner(System.in);
// Default constructor (no-arg) – initialize all three instance variables to 1
public Box() {
this.length = this.width = this.height = 1;
}
// Initial constructor – initialize all three instance variables
public Box(double length, double width, double height) {
this.length = length;
this.width = width;
this.height = height;
}
// Copy constructor – copy Box
public Box(Box b) {
this(b.length, b.width, b.height);
}
// inputWidth, inputLength, and inputHeight methods that set the instance
// variables based on user input have not parameters and do not return a value.
public void inputWidth() {
this.width = input.nextDouble();
}
public void inputLength() {
this.length = input.nextDouble();
}
public void inputHeight() {
this.height = input.nextDouble();
}
// a displayDimensions method that displays the length X Width X height
// (separated by “X”) and does not return a value.
public void displayDimensions() {
System.out.printf("%.2fX%.2fX%.2f%n", length, width, height);
}
// a calcVolume method that has no parameters and calculates the volume of the
// box
public double calcVolume() {
return length * width * height;
}
}
Create a Java class named Package that contains the following:
Package should have three private instance variables of type double named length, width, and height.

Rectangle Class and containsPoint Method

I am trying to understand the Rectangle Class and MyCircle class, specifically the containsPoint methods in each one.
Here is the code:
public class MyRectangle extends GridItem {
private int height;
private int width;
public MyRectangle(int xValue, int yValue, int w, int h) {
x = xValue;
y = yValue;
width = w;
height = h;
}
public double getArea() {
return height * width;
}
public boolean containsPoint(int xValue, int yValue)
{
return xValue >= x &&
xValue <= x + width &&
yValue >= y &&
yValue <= y + height;
}
}
The confusion I'm having is, what does the containsPoint method mean?
How was this current code set up in this particular way, since isn't that supposed to return a boolean and not data types of the int?
Same dilemma for the MyCircle class.
public class MyCircle extends GridItem {
private int radius;
public MyCircle(int xValue, int yValue, int r)
{
x = xValue;
y = yValue;
radius = r;
}
public double getArea() {
return Math.PI * Math.pow(radius, 2);
}
public boolean containsPoint(int xValue, int yValue) {
double dx = x - xValue;
double dy = y - yValue;
double distance = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
return distance <= radius;
}
}
What exactly are they meaning by the containsPoint method?
How do you interpret this?
Been stumped for days and this is part of a bigger assignment, but cannot comprehend the containsPoint method so it's affect the development of mySquare class.....
So far I've got this..
public class MySquare extends GridItem
{
private int side;
public MySquare(int xValue, int yValue, int s)
{
x = xValue;
y = yValue;
side = s;
}
#Override
public double getArea()
{
return side*side;
}
#Override
public boolean containsPoint(int xValue, int yValue)
{
return x && y;
}
}
How does one apply the containsPoint method in the Square class?
Thanks!
what does the containsPoint method mean?
The method just checks if the given point (the given x,y coordinates i.e. xValue, yValue) is within the current Square or Rectangle.
How was this current code set up in this particular way, since isn't that supposed to return a boolean and not data types of the int?
The method arguments are int because they indicate the x and y coordinates for the given point.
Been stumped for days and this is part of a bigger assignment, but cannot comprehend the containsPoint method so it's affect the development of mySquare class.....
Your sub-classes such as the Sqaure class is supposed to have a set of attributes such as x, y, width, height which indicates the position and size of the square. Based on this set of attributes, check if any given point (xValue, yValue) is within your current square. The same applies for Rectangle class.
The containsPoint is the method to check if a point is inside a specific rectangle / circle / shapes on 2D plane.
Comparing variables with each other will result in an boolean value.
Each comparison in containsPoint() in MyRectangle yields a boolean value which are then connected via and. This means that it will only return true if every single comparison yields true.
You would need to apply the same principle to MySquare.
Think about how the coordinates of the square compare to the coordinates of a point if the point is inside the square.
Let's consider the containsPoint of Rectangle.
Let's assume you have a rectangle of height 2 and width 3 starting at co-ordinate (1,1). So your rectangle would look like this
(1,3) (4,3)
------------
| |
| |
------------
(1,1) (4,1)
(In the above example) given two points xValue and yValue, containsPoint returns true if
xValue is between 1 and 4 (inclusive) and
yValue is between 1 and 3 (inclusive)
and false otherwise
Thus, containsPoint tells whether a given point lies on/within a shape.
The containsPoint method of a circle also does the same thing (whether a point lies within/on the circle), however the formula is a bit more involved. You can refer to the Euclidean distance for two dimensions to understand it better.
The containsPoint for a Square will be very similar to that of a rectangle except for using width and heigth, you would have only one side.
return xValue >= x &&
xValue <= x + side &&
yValue >= y &&
yValue <= y + side;

Code works fine, just want to know why I don't need a set method for Perimeter and Area but for width and length

import java.util.Scanner;
public class Rectangle {
private double length, width;
Scanner scan = new Scanner(System.in);
public Rectangle(double length, double width){
this.length = length;
this.width = width;
}
public void setLength(double l){
length = l;
}
public double getLength(){
return length;
}
public void setWidth(double w){
w = width;
}
public double getWidth(){
return width;
}
public double getArea(){
return length*width;
}
public double getPerimeter(){
return ((2*length) + (2*width));`enter code here`
}
}
Why don't I need a set method for Area and Perimeter? Also does it matter if you make the code this.length = length as compared to length = l?
Think about it this way: how would you implement a setter for the perimeter or the area property?
There is no good way of doing it that would make reasonable sense to users of your class: let's say the width is 10 and the height is 7, and a call arrives to set the perimeter to 24. Would you adjust the height, the width, or both in order to satisfy the new value of the perimeter? There is no usable solution to this problem.
Area and Perimeter are so-called calculated properties, i.e. properties computed from values of settable properties. That is why neither area nor perimeter can have a setter.

Variable isn't initialized when trying to use methods

calculateArea(Length, Height, Width);
double area;
calculateCost(area);
}
public static double calculateArea(int l, int h, int w) {
//Variables
double area;
//Length = l;
// Height = h;
//Width = w;
//Find the area
area = l * h * w;
//returns area outside the method
return area;
}
public static void calculateCost(double ar)
PaintCalculator.java:39: error: variable area might not have been initialized
calculateCost(area);
^
1 error
I can't figure out why it isn't initialized when I returned the value for area in the calculateArea method. I've tried declaring and initializing the double area; above calculateCost, but I'm stumped as to why area inside the calculateCost is set to double the area.
You must assign your variable area to your function calculateArea:
double area = calculateArea(Length, Height, Width);
calculateCost(area);
the value for area is currently null, set it equal to something or use the other method you have shown to calculate the area

issues with use of this keyword in java

I am new to java and trying to understand the use of this keyword in java.As per documentation if instance and local variables have same name then local variables mask the instance variables.We use this keyword so that instance variable may not be masked by local variable.Below is the program i was writing to understand the use of this key work but even after use of this keyword instance variable is still getting masked.
class Box{
int height=5;
int length=10;
int breadth=15;
int CalcVol(){
int vol = height*breadth*length;
return vol;
}
Box(int height, int length,int breadth){
this.height = height;
length = length;
breadth = breadth;
System.out.println("height is " + height);
}
}
class MyBox{
public static void main(String args[]){
Box mybox1 = new Box(10, 20, 30);
int vol=mybox1.CalcVol();
System.out.println("volume is" + vol);
}
}
What i am thinking is that variable "height" printed in Box constructor should print 5 ie value of instance variable but its printing 10 ie the value passed as parameter.Please help me on this.
You need to add this before every field you want to access :
Box(int height, int length,int breadth){
// ...and move this statement to the beginning, otherwise this.height gets overriden.
System.out.println("height is " + this.height);
this.height = height;
this.length = length;
this.breadth = breadth;
}
Otherwise, length = length and breadth = breadth have no effect.
It is a name collision problem.
Within the constructor Box are the parameters height, length, and breadth. Those are also names of three fields within Box.
In Java, one considers member variables and block variables to be "closer" than field variables. As such, if you use the exact same name for both (as you have done), the assignment
height = height
will assign the parameter height to the exact same value it held (effectively a noop).
To avoid this issue, you will specify which height you are assigning.
this.height = height;
which is shorthand for "this class's height" or "the field height". When there is no name collision, the compiler will assume you meant the field variable; because there is nothing else with that name in the block.
As an aside, this is a really good reason to learn how to use the final keyword. Final means that the variable can be assigned once, and only once. It prevents it from being reassigned in situations you probably would never want.
For example
public Box(final int height, final int width, final int breadth) {
would then throw a compliation error upon
height = height;
because you are reassigning the value of height. Such techniques are very valuable when writing code, because they prevent you from writing something you think is a field assignment, when you really wrote a parameter assignment.
For your class:
class Box{
int height=5;
int length=10;
int breadth=15;
Box(int height, int length,int breadth){
this.height = height;
length = length;
breadth = breadth;
System.out.println("height is " + height);
}
}
When you construct Box, the following is happening:
Instance variable height is being set to the constructor parameter height
Constructor parameter length is being set to itself (not changing instance variable length)
Constructor parameter breadth is being set to itself (not changing instance variable breadth).
What you probably want to do in the constructor is set your instance variables with the values passed into the constructor like this:
Box(int height, int length,int breadth){
this.height = height;
this.length = length;
this.breadth = breadth;
}
You are performing an assignment here, which will make this.height take on the value of the parameter height.
this.height = height;
If you want to print the original value of this.height, put the print above the assignment and print with this.height.
System.out.println("height was " + this.height);
More completely, your constructor should look like this. Note that you need to prefix with the this keyword on every access to any instance variable that is shadowed by a local variable.
Box(int height, int length,int breadth){
System.out.println("height was " + this.height);
this.height = height;
this.length = length;
this.breadth = breadth;
}
Rather than not understanding the usage of the this keyboard in Java, I think OP isn't understanding object oriented programming in general, seeing how he's trying to print out "5" when the value has already changed. The this keyword becomes a lot less confusing once you understand that concept.
Suppose you have your class Box, and it only has one value, height:
class Box {
// This is a instance variable, that is, each new instance of Box
// has a different height variable even if they are all equal to 5
// initially. It's a different variable in memory.
int height = 5;
// Here's our constructor that sets this instance's value of height
Box(int height){
this.height = height;
}
When you make a new Box, you are making a new Box Object - for each object the height will initially start at 5, but you are changing the height of that instance of Box in your constructor.
Box box1 = new Box(10); // Height was originally 5, but changed to 10 in the constructor
Box box2 = new Box(20); // Height was originally 5, but changed to 20 in the constructor
Box box3 = new Box(30); // Height was originally 5, but changed to 30 in the constructor
When you get to the following line of code in your original program:
System.out.println("height is " + height);
It doesn't matter if it was this.height or height, it will never return 5. You already changed the value of the instance's height in the constructor.
So then. How do we print out a default height of 5? You can't. Not with the same variable name. You have to define constants in the class (like final int HEIGHT = 5) which represent the default values for that class, or use another constructor that doesn't set those values.
class Box{
int height=5;
int length=10;
int breadth=15;
int CalcVol(){
int vol = height*breadth*length;
return vol;
}
Box() {
System.out.println("height is " + height);
}
Box(int height, int length,int breadth) {
this.height = height;
this.length = length;
this.breadth = breadth;
System.out.println("height is " + height);
}
}
class MyBox{
public static void main(String args[]){
Box mybox1 = new Box(10, 20, 30); // this will never print 5, and always 10
Box mybox2 = new Box(); // this will always print 5
}
}
However, if you move the print statement above the assignment and used this.height, like Maxim Bernard did, then it will print out 5, since we didn't change the value yet.
Box(int height, int length,int breadth) {
System.out.println("height is " + this.height); // this will print out 5
this.height = height;
this.length = length;
this.breadth = breadth;
}
If this is really confusing, rather than trying to understand Java's this keyword I suggest just reading a few articles on OOP. You'll understand then that this simply means the current instance of a class.

Categories

Resources